CORS & Preflight Simulator · Node.js Express + React (Vite)

Node.js Express + React (Vite) CORS Config Simulator & Fix Guide

Simulate Fetch Standard preflight (OPTIONS) triggers, credential rules, and origin matching between React (Vite) 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 (React (Vite))

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:5173'],
  methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization'],
  credentials: false,
  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

HTTP method "PATCH" is not a CORS-safelisted method (only GET, HEAD, and POST skip preflight). 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.

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:5173', 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:5173
Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Max-Age: 86400
Vary: Origin, Access-Control-Request-Method, Access-Control-Request-Headers
Actual Response (PATCH)
HTTP/1.1 200 OK
Access-Control-Allow-Origin: http://localhost:5173
Vary: Origin

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

Typical Browser Console Error (React (Vite) → Node.js Express)

When cross-origin headers are missing, mismatched, or blocked during preflight between React (Vite) 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:5000/api/tasks/19' from origin 'http://localhost:5173' has been blocked by CORS policy: Method PATCH is not allowed by Access-Control-Allow-Methods in preflight response.

Why CORS Blocks Requests Between React (Vite) and Node.js Express

Building a decoupled MERN or TypeScript monorepo with React (Vite) on http://localhost:5173 and an Express REST API on http://localhost:5000 is fast and ergonomic, yet almost every team runs into CORS policy blocks the very first time a React component dispatches a JSON POST, PATCH, or DELETE mutation. Even if simple GET /api/tasks requests pass during initial prototyping, mutating endpoints introduce non-safelisted HTTP methods and Content-Type: application/json headers that compel the browser to issue an OPTIONS preflight check.

When developers manually write res.setHeader("Access-Control-Allow-Origin", "*") inside a custom Express middleware instead of adopting the battle-tested cors package, they frequently omit PATCH or DELETE from Access-Control-Allow-Methods, forget to authorize the Authorization header in Access-Control-Allow-Headers, or neglect to short-circuit OPTIONS requests with HTTP 204 before body parsers, rate limiters, and JWT verification run.

Another notorious surprise for Express + Vite developers on macOS is port 5000 colliding with Apple's built-in AirPlay Receiver daemon, which binds to port 5000 and returns HTTP 403 Forbidden with zero CORS headers. Chrome reports that AirPlay 403 response as a CORS error, sending developers down a multi-hour Express debugging spiral when their Express server was never even receiving the HTTP request.

As your Express API and React Vite client grow across development, preview, and production environments, keeping CORS configuration deterministic prevents last-minute deployment blockers. Load allowed origins from a comma-separated environment variable, trim trailing slashes defensively during server startup, and verify that both Express error handlers and 404 fallback routes execute after app.use(cors(corsOptions)). Testing PATCH, PUT, and DELETE mutations directly from your Vite dev server on http://localhost:5173, rather than hiding CORS behind a dev-only proxy, ensures your production API headers are verified continuously.

Step-by-Step Node.js Express + React (Vite) CORS Fix Guide

Follow each step below in order to eliminate preflight failures and lock down production origins safely for Node.js Express.

  1. 1Configure Express cors() With Explicit Vite Origin and All REST Methods

    server/src/app.ts

    Use the official cors package with an explicit CLIENT_ORIGIN allowlist, uppercase REST methods (including PATCH and DELETE), and explicit allowedHeaders. Setting optionsSuccessStatus: 204 ensures clean, empty preflight responses across modern browsers and reverse proxies.

    server/src/app.tstypescript
    import express from 'express';
    import cors from 'cors';
    
    const app = express();
    
    const corsOptions: cors.CorsOptions = {
      origin: [
        process.env.CLIENT_ORIGIN ?? 'http://localhost:5173',
      ],
      methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
      allowedHeaders: ['Content-Type', 'Authorization'],
      credentials: false,
      maxAge: 86400,
      optionsSuccessStatus: 204,
    };
    
    app.use(cors(corsOptions));
    app.use(express.json());
    
    app.patch('/api/tasks/:id', (req, res) => {
      res.json({ id: req.params.id, updated: req.body });
    });
    
    export default app;
  2. 2Avoid Port 5000 Collisions and Verify the Active Express Listener

    server/.env

    On macOS Monterey and newer, AirPlay Receiver listens on port 5000 and responds with 403 Forbidden without CORS headers. Either disable AirPlay Receiver in System Settings or move Express to port 4000 or 5050 so React always reaches your Node process.

    server/.envdotenv
    PORT=5000
    CLIENT_ORIGIN=http://localhost:5173
  3. 3Keep Express Error Handlers Registered Below CORS Middleware

    server/src/middleware/errorHandler.ts

    When route handlers throw errors or call next(err), Express forwards control to your 4-argument error middleware. Because cors(corsOptions) already executed earlier in the request lifecycle, Access-Control-Allow-Origin remains attached to 400, 404, and 500 JSON responses so React can display meaningful error toasts.

    server/src/middleware/errorHandler.tstypescript
    import type { ErrorRequestHandler } from 'express';
    
    export const errorHandler: ErrorRequestHandler = (err, _req, res, _next) => {
      const status = typeof err.status === 'number' ? err.status : 500;
      res.status(status).json({
        error: err.message || 'Internal Server Error',
      });
    };
  4. 4Send Typed PATCH Requests From React (Vite)

    client/src/api/tasks.ts

    Centralize your API base URL in Vite environment variables (VITE_API_URL) so local, staging, and production builds switch origins cleanly without touching component fetch logic.

    client/src/api/tasks.tstypescript
    const API_URL = import.meta.env.VITE_API_URL ?? 'http://localhost:5000';
    
    export async function updateTaskStatus(id: string, completed: boolean, token: string) {
      const res = await fetch(`${API_URL}/api/tasks/${id}`, {
        method: 'PATCH',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify({ completed }),
      });
    
      if (!res.ok) {
        throw new Error(`Task update failed (${res.status})`);
      }
    
      return res.json();
    }

Common Node.js Express + React (Vite) 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

macOS AirPlay Receiver Hijacking Port 5000 With Fake CORS Errors

If your Express backend defaults to port 5000 on macOS and fails to bind (or binds only IPv4 while localhost resolves IPv6 ::1 to AirPlay), the browser receives a 403 Forbidden from Apple's AirTunes server without CORS headers. Always inspect the Response Headers tab in DevTools for Server: AirTunes.

Pitfall 2

Case-Sensitive Method Typos or Omitting PATCH From Allowed Methods

Per RFC 9110, HTTP method tokens are case-sensitive. Returning Access-Control-Allow-Methods: GET, POST, PUT, DELETE (forgetting PATCH, or writing lowercase patch) causes browsers to reject PATCH mutations during preflight validation.

Pitfall 3

Rate Limiters Rejecting OPTIONS Preflights With HTTP 429

Mounting express-rate-limit before cors() counts OPTIONS preflight requests against your API quota and returns 429 Too Many Requests without CORS headers once triggered. Always mount cors() ahead of rate limiters and authentication checks.

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 Socket.IO & WebSockets (Upgrade & 3600s).

Open Nginx Builder

Frequently Asked Questions

Why does GET work from React Vite to Express, but PATCH or POST fails with CORS?
A simple GET request without custom headers does not trigger an OPTIONS preflight. Sending PATCH or POST with Content-Type: application/json or an Authorization header forces the browser to send an OPTIONS preflight first, which fails if Express does not explicitly permit both the HTTP method and request headers.
Can I use Access-Control-Allow-Origin: * if my React app uses Bearer tokens in Authorization?
If your React app only sends Authorization: Bearer headers (with no cookies and credentials omitted), wildcard * origin is technically permitted by the Fetch Standard; HOWEVER, wildcard * in Access-Control-Allow-Headers does NOT authorize Authorization. You must still list Authorization explicitly in allowedHeaders, and whitelisting your exact origin is better security hygiene.
Should I enable CORS in Express if I use Vite server.proxy locally?
Yes, unless your production hosting also reverse-proxies /api on the exact same domain as your static React files. If React is hosted on Cloudflare Pages or Netlify and Express runs on Render, Fly.io, or Railway, Express must emit valid CORS headers in production.
How do I debug which header caused Express CORS to fail?
Open Chrome DevTools -> Network -> click the red OPTIONS request -> compare the Request Headers (Access-Control-Request-Method and Access-Control-Request-Headers) against the Response Headers (Access-Control-Allow-Methods and Access-Control-Allow-Headers). Every requested method and header must be explicitly covered.
Browse all 12 stacks →