Logo

dev-resources.site

for different kinds of informations.

Cookies auto clearing after browser refresh issue , CORS related express cookies issue

Published at
1/12/2025
Categories
express
cookies
cors
node
Author
tigawanna
Categories
4 categories in total
express
open
cookies
open
cors
open
node
open
Author
9 person written this
tigawanna
open
Cookies auto clearing after browser refresh issue , CORS related express cookies issue

This error is a combination of CORS issues and incorrect cookie settings.
To resolve you need to set your server to allow cookies and set the same origin policy to allow the frontend to make requests to your backend server.

cors

// cors-utils.ts
import type { Request, Response, NextFunction } from "express";

export function corsHeaders(req: Request, res: Response, next: NextFunction) {
  if (!req.headers.origin) return next();
  if (allowedOrigins.includes(req.headers.origin)) {
    res.setHeader("Access-Control-Allow-Credentials", "true");
    res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
    next();
  }
}
export const allowedOrigins = [
  "http://localhost:3000",
  process.env.FRONTEND_URL ?? "",
];
Enter fullscreen mode Exit fullscreen mode
//  app.ts
app.use(corsHeaders);
app.use(
  cors({
    origin: (origin, callback) => {
      if ((origin && allowedOrigins.indexOf(origin) !== -1) || !origin) {
        callback(null, true);
      } else {
        callback(new Error("Not allowed by CORS"));
      }
    },
    optionsSuccessStatus: 200,
  }),
);
Enter fullscreen mode Exit fullscreen mode

and create the cookies using the options

import jwt from "jsonwebtoken";
const { sign, verify } = jwt;

const accessTokencookieOptions = {
      httpOnly: true,
      secure:true,
      sameSite: "none",
      path: "/",
      maxAge: 12 * 60 * 1000, // expires in 12 minutes
}

const accessTokebCookieKey = "rfsh-token";
  const fiftenMinutesInSeconds = Math.floor(Date.now() / 1000) + 60 * 15; // 15 minutes
  const accessToken = await sign(
    { ...sanitizedPayload, exp:  : fiftenMinutesInSeconds },
    ACCESS_TOKEN_SECRET,
  );
  res.clearCookie(accessTokebCookieKey, accessTokencookieOptions);
  res.cookie(accessTokebCookieKey, accessToken, accessTokencookieOptions);
Enter fullscreen mode Exit fullscreen mode
express Article's
30 articles in total
Favicon
Cookies auto clearing after browser refresh issue , CORS related express cookies issue
Favicon
how to setup express api from scratch
Favicon
I Really like Middleware in NodeJs/Express.
Favicon
From Legacy to Lightning: Modernizing an Astro App with Daytona
Favicon
Setting Up Dual Compilation (SSR + CSR) in ViteJS with vite-plugin-builder
Favicon
Starting A Series On TypeScript Join In As We Build Together
Favicon
How to Generate a Secure JWT Secret Using Node.js
Favicon
Mastering Express.js: A Deep Dive
Favicon
Comprendre le Design Pattern MVC avec Node.js, Express et MongoDB
Favicon
How to implement File uploads in Nodejs: A step by step guide
Favicon
Node backend port band bo'lib qolishi
Favicon
Deploying an Existing Express API + Prisma + Supabase Project to Vercel
Favicon
New React Library: API Integration Made Easy with Axiosflow's Automatic Client Generation
Favicon
Build and Deploy a Monorepo WebSocket web application with Turbo, Express, and Vite on Render Using Docker
Favicon
Express app with decorators based routing and dependency injection
Favicon
miniframe-router: Router for Express.JS Applications
Favicon
Create an API for AG-Grid with Express
Favicon
Blogsphere | A blogging website made with MERN stack. includes user management.
Favicon
วิธีทำ Auth API ด้วย Express, JWT, MySQL และ Prisma
Favicon
[Boost]
Favicon
Complete, full-stack setup for any node/express/psql app, equipped with basic ui, routes & more.
Favicon
Which One Should You Choose NEST JS or EXPRESS JS?
Favicon
Hackers Love These Common MERN Stack Mistakes: Are You Exposing Your App? 🔐
Favicon
Build a React login page template
Favicon
A New Way of Setting Up an Express Server for Lazy Developers npm i mbfi
Favicon
[Boost]
Favicon
Express request types
Favicon
Mastering Express.js: A Deep Dive
Favicon
Getting Started with Express.js for Web Development
Favicon
Introduction to TypeScript with Express: Building Your First REST API

Featured ones: