Back to blogs
Blog
Writing in public
Longer posts — published here first, then cross-posted to Dev.to with a canonical URL back to this site.
Blog
Longer posts — published here first, then cross-posted to Dev.to with a canonical URL back to this site.
Back to blogs
Back to blogs
Postexpress, cookies, cors, node
This error is a combination of CORS issues and incorrect cookie settings. To resolve you need to set...
Date published

Discriminated unions (also known as tagged unions) are a powerful TypeScript pattern that enables...

Why You Might Still Pick Next.js Over TanStack Start From a TanStack Start...

A complete theme management system for React applications with SSR support! ✨ 🌟...
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
1// cors-utils.ts2import type { Request, Response, NextFunction } from "express";34export function corsHeaders(req: Request, res: Response, next: NextFunction) {5 if (!req.headers.origin) return next();6 if (allowedOrigins.includes(req.headers.origin)) {7 res.setHeader("Access-Control-Allow-Credentials", "true");8 res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");9 next();10 }11}12export const allowedOrigins = [13 "http://localhost:3000",14 process.env.FRONTEND_URL ?? "",15];
1// app.ts2app.use(corsHeaders);3app.use(4 cors({5 origin: (origin, callback) => {6 if ((origin && allowedOrigins.indexOf(origin) !== -1) || !origin) {7 callback(null, true);8 } else {9 callback(new Error("Not allowed by CORS"));10 }11 },12 optionsSuccessStatus: 200,13 }),14);
and create the cookies using the options
1import jwt from "jsonwebtoken";2const { sign, verify } = jwt;34const accessTokencookieOptions = {5 httpOnly: true,6 secure:true,7 sameSite: "none",8 path: "/",9 maxAge: 12 * 60 * 1000, // expires in 12 minutes10}1112const accessTokebCookieKey = "rfsh-token";13 const fiftenMinutesInSeconds = Math.floor(Date.now() / 1000) + 60 * 15; // 15 minutes14 const accessToken = await sign(15 { ...sanitizedPayload, exp: : fiftenMinutesInSeconds },16 ACCESS_TOKEN_SECRET,17 );18 res.clearCookie(accessTokebCookieKey, accessTokencookieOptions);19 res.cookie(accessTokebCookieKey, accessToken, accessTokencookieOptions);