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:
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.
1Configure Express cors() With Explicit Vite Origin and All REST Methods
server/src/app.tsUse 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.tstypescriptimport 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;2Avoid Port 5000 Collisions and Verify the Active Express Listener
server/.envOn 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/.envdotenvPORT=5000 CLIENT_ORIGIN=http://localhost:51733Keep Express Error Handlers Registered Below CORS Middleware
server/src/middleware/errorHandler.tsWhen 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.tstypescriptimport 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', }); };4Send Typed PATCH Requests From React (Vite)
client/src/api/tasks.tsCentralize 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.tstypescriptconst 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.
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.
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.
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.
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 Socket.IO & WebSockets (Upgrade & 3600s).
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.
Related CORS Stack Simulators
Browse all 12 stacks →Node.js Express + Next.js App Router CORS Simulator & Fix Guide
Fix CORS preflight and cookie credential errors between Node.js Express APIs and Next.js App Router. Configure cors() middleware, app.options, and Helmet.
Laravel + React (Vite) CORS Config Simulator & Fix Guide
Simulate and fix CORS preflight errors between Laravel 11/12 APIs and React Vite on port 5173. Generate config/cors.php with credentials and header rules.
FastAPI + React (Vite) CORS Config Simulator & Fix Guide
Simulate and resolve CORS errors between Python FastAPI and React Vite on port 5173. Fix preflight OPTIONS failures, Pydantic 422 responses, and upload headers.
Cloudflare Workers API + SPA Frontend CORS Simulator & Fix Guide
Fix CORS preflight failures between Cloudflare Workers APIs and static SPAs on Pages, Vercel, or Netlify. Handle OPTIONS 204, immutable headers, and Vary.