Express makes CORS relatively painless, but there are a few gotchas that catch people off guard. Let me walk through every setup I’ve seen work in production.
The cors Package (Easiest Option)#
npm install corsThe One-Liner (Development Only)#
const cors = require('cors');
app.use(cors());This allows all origins, all methods, all headers. Fine for local development. Do NOT use this in production.
Allow a Single Origin#
const cors = require('cors');
app.use(cors({
origin: 'https://myapp.com',
methods: ['GET', 'POST', 'PUT', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization'],
credentials: true,
maxAge: 86400,
}));Allow Multiple Origins#
This is where it gets slightly tricky. The cors package doesn’t accept an array for origin — it accepts a function: