Typical Browser Console Error (Next.js App Router → Node.js Express)
When cross-origin headers are missing, mismatched, or blocked during preflight between Next.js App Router and Node.js Express, Chrome and Firefox log an error matching the pattern below in DevTools:
Access to fetch at 'http://localhost:4000/api/auth/session' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Why CORS Blocks Requests Between Next.js App Router and Node.js Express
Many full-stack TypeScript teams run a dedicated Node.js Express API on http://localhost:4000, handling WebSockets, background job triggers, or shared mobile and web endpoints, alongside a Next.js App Router web application on http://localhost:3000. Because Express is intentionally minimal and unopinionated, it emits zero CORS headers by default, and even after installing the official cors npm package, subtle middleware ordering mistakes or Helmet security defaults regularly break browser preflight checks.
A particularly common production bug in Express + Next.js stacks occurs when developers mount app.use(cors()) AFTER route handlers, AFTER authentication middleware that rejects unauthenticated OPTIONS requests with HTTP 401 Unauthorized, or without an explicit origin allowlist when credentials: true is enabled for HttpOnly JWT cookies or express-session cookies. Because Next.js Server Components do not send a browser Origin header, your Express origin validator must also permit undefined origins safely without opening your API to arbitrary websites.
Additionally, Express v5 changed wildcard path syntax (requiring named wildcards like "/{*splat}" instead of bare "*" in route matchers), and Helmet's default Cross-Origin-Resource-Policy: same-origin header can block cross-origin images, PDFs, or media served from Express to Next.js even after Access-Control-Allow-Origin is configured accurately.
When deploying Node.js Express alongside Next.js App Router across separate cloud hosts, such as Next.js on Vercel and Express on Fly.io, Railway, or AWS ECS, remember to set app.set("trust proxy", 1) in Express if you rely on secure HttpOnly cookies behind TLS termination. Always inspect the Network tab for two separate checks: first, that OPTIONS preflights return 204 No Content without triggering authentication middleware or rate limits; second, that Express never leaks Access-Control-Allow-Origin: * alongside Access-Control-Allow-Credentials: true, which browsers immediately reject under the Fetch Standard.
Step-by-Step Node.js Express + Next.js App Router CORS Fix Guide
Follow each step below in order to eliminate preflight failures and lock down production origins safely for Node.js Express.
1Install the Official Express cors Middleware and TypeScript Types
terminal (Express API root)Install the standard cors middleware package (and @types/cors for strict TypeScript projects) rather than hand-writing ad-hoc res.header() calls that commonly miss Vary: Origin, dynamic allowlist checks, or 204 OPTIONS preflight short-circuiting.
terminal (Express API root)bashnpm install cors npm install -D @types/cors2Configure Dynamic Origin Validation and Register CORS First
src/server.tsMount cors(corsOptions) at the very top of your Express middleware chain; right after helmet (with crossOriginResourcePolicy adjusted if serving media) and before express.json(), auth guards, and routers. Using an origin callback supports multiple Next.js environments cleanly while allowing non-browser Server Component calls.
src/server.tstypescriptimport express from 'express'; import cors, { type CorsOptions } from 'cors'; import helmet from 'helmet'; const app = express(); const allowedOrigins = new Set( (process.env.ALLOWED_ORIGINS ?? 'http://localhost:3000') .split(',') .map((o) => o.trim().replace(/\/+$/, '')) ); const corsOptions: CorsOptions = { origin(origin, callback) { // Allow Next.js Server Components / curl (no Origin header) and whitelisted browser origins if (!origin || allowedOrigins.has(origin)) { callback(null, true); return; } callback(new Error(`CORS blocked for origin: ${origin}`)); }, methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], allowedHeaders: ['Content-Type', 'Authorization', 'X-CSRF-Token'], credentials: true, maxAge: 86400, optionsSuccessStatus: 204, }; app.use(helmet({ crossOriginResourcePolicy: { policy: 'cross-origin' } })); app.use(cors(corsOptions)); app.use(express.json());3Ensure Authentication Middleware Never Intercepts OPTIONS Preflights
src/middleware/requireAuth.tsBrowsers never attach Bearer Authorization tokens to OPTIONS preflight requests. Registering app.use(cors(corsOptions)) before routers already handles OPTIONS globally, and adding an explicit OPTIONS guard inside route-level auth middleware provides safe defense in depth.
src/middleware/requireAuth.tstypescriptimport type { Request, Response, NextFunction } from 'express'; export function requireAuth(req: Request, res: Response, next: NextFunction) { if (req.method === 'OPTIONS') { res.sendStatus(204); return; } const authHeader = req.headers.authorization; if (!authHeader?.startsWith('Bearer ')) { res.status(401).json({ error: 'Missing bearer token' }); return; } next(); }4Call the Express API From Next.js Client Components With Credentials
src/lib/expressClient.tsWhen calling Express from a Next.js Client Component, set credentials: "include" whenever Express sets HttpOnly cookies (such as connect.sid or refresh tokens), and never add mode: "no-cors", which produces an unreadable opaque response.
src/lib/expressClient.tstypescript'use client'; const EXPRESS_API = process.env.NEXT_PUBLIC_EXPRESS_URL ?? 'http://localhost:4000'; export async function verifySession(csrfToken: string) { const response = await fetch(`${EXPRESS_API}/api/auth/session`, { method: 'POST', credentials: 'include', headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': csrfToken, }, body: JSON.stringify({ refresh: true }), }); if (!response.ok) { throw new Error(`Express API error: ${response.status}`); } return response.json(); }
Common Node.js Express + Next.js App Router CORS Pitfalls
Even when your basic origin string looks correct, these three framework-specific edge cases frequently reintroduce CORS failures in staging and production environments.
Using origin: true Blindly in Production With credentials: true
Passing origin: true to Express's cors middleware reflects whatever Origin header an attacker sends directly into Access-Control-Allow-Origin. Combined with credentials: true, any malicious website can execute authenticated requests using your users' cookies and exfiltrate private JSON responses.
Helmet Default Cross-Origin-Resource-Policy Blocking Images and Files
Calling app.use(helmet()) with default settings emits Cross-Origin-Resource-Policy: same-origin. Even with valid CORS headers, Chrome blocks Next.js from embedding images, PDFs, or media served from Express unless crossOriginResourcePolicy is explicitly set to cross-origin.
Setting mode: "no-cors" in Next.js Fetch Calls
Chrome's CORS console message mentions mode: "no-cors", tempting developers to add it to fetch(). In reality, no-cors strips custom headers like Authorization, forbids application/json, and returns an empty opaque response (status 0) whose body JavaScript cannot inspect.
Deploying Behind Nginx? Eliminate CORS Preflights or Configure Your Proxy
Configure TLS, WebSocket headers, and X-Forwarded-Proto, or serve your frontend and /api/ on the same origin with Nginx Reverse Proxy Config for Node.js Express & PM2 (trust proxy & SSL).
Frequently Asked Questions
- Why does Express cors() still fail if I put app.use(cors()) after app.use("/api", routes)?
- Express executes middleware strictly in top-to-bottom registration order. If your route handler or auth middleware executes before app.use(cors()), the response is flushed, or rejected with 401/404, without Access-Control-Allow-Origin ever being set. Always mount app.use(cors(corsOptions)) before all routes.
- Do I need app.options("*", cors(corsOptions)) if I already use app.use(cors(corsOptions))?
- When app.use(cors(corsOptions)) is mounted globally at the top of the app, it already intercepts OPTIONS preflight requests and responds with 204 No Content. You only need explicit app.options() calls when applying CORS selectively to specific routes (and in Express 5, use "/{*splat}" rather than "*").
- Why does Next.js not send my Express session cookie in production?
- Verify four aligned settings on Express: credentials: true in corsOptions, credentials: "include" in Next.js fetch, cookie.sameSite set appropriately ("lax" for shared root domain subdomains or "none" with cookie.secure: true over HTTPS), and app.set("trust proxy", 1) when running Express behind Nginx, Cloudflare, or Railway.
- How does cors middleware handle Vary: Origin automatically?
- Whenever origin is configured as a specific string, array, regex, or callback function rather than static "*", the Express cors package automatically appends Vary: Origin to responses so CDNs and browser caches never serve one origin's CORS headers to another.
Related CORS Stack Simulators
Browse all 12 stacks →Node.js Express + React (Vite) CORS Config Simulator & Fix Guide
Resolve CORS preflight errors between Node.js Express APIs and React Vite on port 5173. Generate cors() configs, fix PATCH/DELETE methods, and debug headers.
Laravel API + Next.js App Router CORS Simulator & Fix Guide
Debug CORS between Laravel 11/12 APIs and Next.js App Router on port 3000. Separate Server Component fetches from Client Component browser preflights.
FastAPI + Next.js CORS Config Simulator & Fix Guide
Fix CORS preflight failures between Python FastAPI (Uvicorn) and Next.js on port 3000. Configure CORSMiddleware order, trailing redirects, and credentials.
Next.js Route Handlers + External Frontend CORS Simulator & Fix Guide
Configure CORS for Next.js App Router Route Handlers serving external SPAs or widgets. Fix 405 OPTIONS preflights, next.config.ts headers, and Vary: Origin.