Fix CORS in Express

Last updated: April 2026

Browser Console Error
Access to fetch at 'http://localhost:3000/api' from origin 'http://localhost:5173' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present.

Install the cors package and mount it before your routes. The middleware must run before any route handler to handle preflight OPTIONS requests correctly.

Test your Express CORS live โ†’

Basic fix โ€” install and add cors middleware

npm install cors
const express = require('express');
const cors = require('cors');

const app = express();

// Mount CORS before routes
app.use(cors({
  origin: 'https://yourapp.com',
  credentials: true,
}));

app.use(express.json());
// ... your routes

Multiple origins (dev + production)

const allowedOrigins = [
  'http://localhost:5173',  // Vite
  'http://localhost:3000',  // CRA
  'https://yourapp.com',
];

app.use(cors({
  origin: function(origin, callback) {
    // allow requests with no origin (curl, Postman)
    if (!origin) return callback(null, true);
    if (allowedOrigins.includes(origin)) {
      return callback(null, true);
    }
    return callback(new Error('CORS: origin not allowed'));
  },
  credentials: true,
}));

Wildcard origin without credentials

// Safe when not using cookies or session auth
app.use(cors());  // allows all origins, no credentials
โš  Never use origin: '*' with credentials: true. Browsers reject responses with wildcard origin when credentials are included. Use an explicit origin list or origin function instead.

Handle preflight OPTIONS explicitly (if needed)

The cors middleware handles OPTIONS automatically when mounted with app.use(cors()). If you mount it per-route, add an explicit OPTIONS handler:

// Only needed if using cors() per route
app.options('*', cors());
app.post('/api/data', cors({ origin: 'https://yourapp.com' }), handler);

Middleware order matters

// CORRECT โ€” cors before routes and body parser
app.use(cors({ origin: 'https://yourapp.com', credentials: true }));
app.use(express.json());
app.get('/api', handler);

// WRONG โ€” cors after routes means preflight fails
app.get('/api', handler);
app.use(cors()); // too late

Verify your CORS headers

curl -X OPTIONS http://localhost:3000/api \
  -H "Origin: http://localhost:5173" \
  -H "Access-Control-Request-Method: POST" \
  -v 2>&1 | grep -i "access-control"
📚 HttpFixer Blog โ€” fix guides, explainers, and references โ†’