CORS & Preflight Simulator · Node.js Express + Next.js App Router

Node.js Express + Next.js App Router CORS Simulator & Fix Guide

Simulate Fetch Standard preflight (OPTIONS) triggers, credential rules, and origin matching between Next.js App Router and Node.js Express. Copy generated configuration code below.

Written & verified by Chathura Prabashana · Updated November 2026

1. Adjust stack settings or load a test scenario2. Inspect live diagnostics3. Copy generated config
Quick-Test Scenarios:

1. Browser Request (Next.js App Router)

2. Server Response Policy (Node.js Express)

Access-Control-Allow-Methods
// server.ts / app.js — Express CORS Middleware (npm install cors)
import express from 'express';
import cors from 'cors';

const app = express();

const corsOptions: cors.CorsOptions = {
  origin: ['http://localhost:3000'],
  methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization', 'X-CSRF-Token'],
  credentials: true,
  maxAge: 86400,
  optionsSuccessStatus: 204,
};

// Apply before route handlers and explicitly enable preflight handling
app.use(cors(corsOptions));
app.options('*', cors(corsOptions));

Preflight (OPTIONS)

Triggered · Passed

Content-Type "application/json" is not CORS-safelisted (only application/x-www-form-urlencoded, multipart/form-data, and text/plain avoid preflight). Request includes non-safelisted header(s): Authorization, X-CSRF-Token.

Browser Verdict

Allowed

Browser CORS validation passed. JavaScript can read the response body.

Rule Engine Diagnostics

  • Reverse Proxy Tip: Avoid Duplicate CORS Headers in Nginx + Upstream App

    Never configure Access-Control-Allow-Origin in both Nginx and your backend framework simultaneously. Browsers reject duplicate headers with: "The 'Access-Control-Allow-Origin' header contains multiple values '*, http://localhost:3000', but only one is allowed." Choose one layer (or use proxy_hide_header in Nginx).

Simulated HTTP Response Headers

HTTP/1.1
Preflight (OPTIONS)
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: http://localhost:3000
Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS
Access-Control-Allow-Headers: Content-Type, Authorization, X-CSRF-Token
Access-Control-Allow-Credentials: true
Access-Control-Max-Age: 86400
Vary: Origin, Access-Control-Request-Method, Access-Control-Request-Headers
Actual Response (POST)
HTTP/1.1 200 OK
Access-Control-Allow-Origin: http://localhost:3000
Access-Control-Allow-Credentials: true
Vary: Origin

Runs locally in your browser. Origins, endpoints, and headers are never sent to a server.

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:

DevTools Console Output

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.

  1. 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)bash
    npm install cors
    npm install -D @types/cors
  2. 2Configure Dynamic Origin Validation and Register CORS First

    src/server.ts

    Mount 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.tstypescript
    import 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());
  3. 3Ensure Authentication Middleware Never Intercepts OPTIONS Preflights

    src/middleware/requireAuth.ts

    Browsers 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.tstypescript
    import 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();
    }
  4. 4Call the Express API From Next.js Client Components With Credentials

    src/lib/expressClient.ts

    When 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.

Pitfall 1

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.

Pitfall 2

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.

Pitfall 3

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.

Related Tool · Same-Origin Reverse 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).

Open Nginx Builder

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.
Browse all 12 stacks →