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