Skip to content

How to Enable CORS in Express.js (cors Middleware, Express 4 and 5)

Enable CORS in Express with the cors middleware: allow all or specific origins, credentials and cookies, preflight requests, per-route CORS, the Express 5 app.options wildcard error, and CORS without a package. Tested on Express 5.3.

Steps
5
Covers
CORS, Express, JavaScript
Versions & support
About Node.js →
On this page 5 steps

If your frontend runs on a different origin than your Express API (for example React or Vue on http://localhost:5173 and the API on http://localhost:3000, or app.example.com and api.example.com in production), browsers block the API’s responses until the API sends CORS headers:

Access to fetch at 'http://localhost:3000/api/items' from origin 'http://localhost:5173' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

This guide shows how to enable CORS in Express with the official cors middleware: for all origins, for a list of domains, with credentials (cookies), for preflight requests, and per route. It also covers a change in Express 5 that breaks the app.options('*', cors()) line found in many tutorials, and how to write CORS middleware yourself. Every example was tested with Express 5.3, cors 2.8.6 and Node.js 22.

Step 1 of 5Install the cors Package

In your project folder:

npm install cors

cors is maintained by the Express team and works with Express 4 and 5.

Step 2 of 5Allow All Origins

The quickest setup allows every website, which is right for a public API without cookies or login:

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

const app = express();
app.use(cors());

app.get('/api/items', (req, res) => res.json([{ id: 1 }]));

app.listen(3000);

cors() without options sends Access-Control-Allow-Origin: * and answers preflight OPTIONS requests for all routes. Register it before your routes so every response gets the headers. Test it:

curl -s -o /dev/null -D - -H "Origin: https://any.com" http://localhost:3000/api/items
HTTP/1.1 200 OK
Access-Control-Allow-Origin: *

Step 3 of 5Allow Only Your Own Domains

For an API used by your own frontend, list the allowed origins. Each entry must match the page’s origin exactly: scheme, host and port.

app.use(cors({
  origin: ['https://app.example.com', 'http://localhost:5173'],
}));

The middleware compares the request’s Origin with the list, sends back only the matching origin and adds Vary: Origin so caches don’t mix up responses for different sites. Requests from other origins get no Access-Control-Allow-Origin, so the browser blocks them.

For more complex rules, such as all subdomains or origins read from an environment variable, pass a function:

const allowed = (process.env.CORS_ORIGINS || '').split(',');

app.use(cors({
  origin(origin, callback) {
    if (!origin) return callback(null, true);                     // curl, server-to-server, same-origin
    if (allowed.includes(origin)) return callback(null, true);
    if (/^https:\/\/[a-z0-9-]+\.example\.org$/.test(origin)) return callback(null, true);
    callback(null, false);                                         // no CORS headers
  },
}));

Start the app with CORS_ORIGINS=https://app.example.com,https://admin.example.com node server.js. In our test, https://shop.example.org matched the regular expression and was echoed back, while https://evil.com got no CORS headers. Use callback(null, false) to reject; passing an Error instead turns every request from that origin into a 500 error.

Step 4 of 5Cookies, Sessions and Authorization Headers (credentials)

If the frontend sends cookies or HTTP authentication with fetch(url, { credentials: 'include' }) or Axios withCredentials: true, enable credentials. This requires a specific origin list: browsers reject * together with credentials.

app.use('/api', cors({
  origin: ['https://app.example.com', 'http://localhost:5173'],
  credentials: true,
  exposedHeaders: ['X-Total-Count'],
  maxAge: 86400,
}));
  • credentials: true adds Access-Control-Allow-Credentials: true.
  • exposedHeaders lets frontend code read custom response headers, such as a pagination count; without it, response.headers.get('X-Total-Count') returns null.
  • maxAge lets the browser cache the preflight result (in seconds), so it doesn’t send OPTIONS before every request.

The preflight response for a PUT with a JSON body and an Authorization header then looks like this:

curl -s -o /dev/null -D - -X OPTIONS http://localhost:3000/api/items/1 -H "Origin: https://app.example.com" -H "Access-Control-Request-Method: PUT" -H "Access-Control-Request-Headers: content-type,authorization"
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://app.example.com
Vary: Origin, Access-Control-Request-Headers
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: GET,HEAD,PUT,PATCH,POST,DELETE
Access-Control-Allow-Headers: content-type,authorization
Access-Control-Max-Age: 86400
Access-Control-Expose-Headers: X-Total-Count

By default the middleware allows all common methods and reflects whatever headers the browser asks for. To restrict them, add methods: ['GET', 'POST'] and allowedHeaders: ['Content-Type', 'Authorization'].

For cross-site cookies, the cookie itself must also be set with SameSite=None; Secure (HTTPS only), for example res.cookie('sid', id, { sameSite: 'none', secure: true, httpOnly: true }); otherwise the browser won’t send it, even with correct CORS headers.

Step 5 of 5Enable CORS for Specific Routes Only

You can apply cors() to one route or router instead of the whole app:

app.get('/public/stats', cors(), (req, res) => res.json({ users: 42 }));

This works for simple GET requests, but there’s a catch: route-level middleware runs only for that route’s method. Requests that need a preflight (PUT, DELETE, JSON bodies, custom headers) send OPTIONS first, and Express answers it itself, without CORS headers. In our test, the preflight to such a route returned 200 OK with only an Allow header, so the browser blocked the real request. Handle the preflight for that path as well:

app.options('/public/stats', cors());
app.put('/public/stats', cors(), (req, res) => res.json({ ok: true }));

Or simply mount the middleware on a path prefix, which covers all methods including OPTIONS: app.use('/api', cors(options)).

Express 5: app.options(‘*’, cors()) Throws an Error

Many tutorials enable preflight for all routes with app.options('*', cors()). In Express 5, which uses a newer version of path-to-regexp, a bare * is no longer a valid route, and the app crashes on startup:

PathError: Missing parameter name at index 1: *; visit https://git.new/pathToRegexpError for info

You usually don’t need that line at all: app.use(cors()) already answers preflight requests for every route. If you do want a catch-all OPTIONS route in Express 5, name the wildcard:

app.options('/{*splat}', cors());

In Express 4, app.options('*', cors()) still works.

CORS Without the cors Package

For full control, or to avoid a dependency, a small middleware does the same job:

const allowed = ['https://app.example.com', 'http://localhost:5173'];

app.use((req, res, next) => {
  const origin = req.headers.origin;
  if (allowed.includes(origin)) {
    res.set('Access-Control-Allow-Origin', origin);
    res.set('Access-Control-Allow-Credentials', 'true');
    res.vary('Origin');
  }
  if (req.method === 'OPTIONS') {
    res.set('Access-Control-Allow-Methods', 'GET,POST,PUT,PATCH,DELETE');
    res.set('Access-Control-Allow-Headers', 'Content-Type, Authorization');
    res.set('Access-Control-Max-Age', '86400');
    return res.sendStatus(204);
  }
  next();
});

Put it before your routes, body parser and authentication middleware, so preflight requests are answered before anything can reject them.

CORS on Error Responses

Because the middleware sets the headers before your route runs, they are kept on errors from your routes too. In our test, both a thrown error (500 Internal Server Error) and an unknown route under /api (404) still carried Access-Control-Allow-Origin, so the frontend could read the real status and error message. This only works when cors() is registered before the routes and before any middleware that might end the request early, such as authentication or rate limiting.

Express Behind Nginx or Apache

If a reverse proxy in front of Express also adds CORS headers, the browser receives Access-Control-Allow-Origin twice and fails with “The ‘Access-Control-Allow-Origin’ header contains multiple values”. Set CORS in one place only: either in Express, or in the proxy (see CORS in Nginx and CORS in Apache). For local development, a Vite or webpack dev-server proxy avoids CORS entirely; see how to fix CORS errors.

Troubleshooting

ProblemFix
No ‘Access-Control-Allow-Origin’ headerapp.use(cors()) is registered after the routes, or after middleware that already ended the response. Move it to the top. Also check the origin is in your list exactly.
GET works, PUT/DELETE/JSON POST failThe preflight isn’t handled: you used cors() only on a route. Use app.use() or add app.options() for that path.
App crashes with PathError on startExpress 5 and app.options('*', …). Remove it or use '/{*splat}'.
“must not be the wildcard ‘*’ when the request’s credentials mode is ‘include'”Use an origin list with credentials: true.
Cookie isn’t sent despite credentialsSet the cookie with SameSite=None; Secure and use HTTPS; check that the frontend sends credentials: 'include'.
Can’t read a custom response header in JavaScriptAdd it to exposedHeaders.
Every request from one site returns 500Your origin function calls callback(new Error(...)). Use callback(null, false) to reject quietly.

Frequently Asked Questions

Is app.use(cors()) safe in production?

For a public, read-only API, yes. For APIs that use cookies, sessions or return private data, list your own origins instead, and remember that CORS isn’t authentication: other clients like curl ignore it.

Does the cors package work with Express 5?

Yes. We tested cors 2.8.6 with Express 5.3. Only the wildcard route syntax for app.options() changed in Express 5.

Do I need CORS if my frontend and API are on the same domain?

No. If the page and API share scheme, host and port, for example both served by Nginx under https://example.com with the API at /api, the browser makes no CORS check.

How do I allow localhost during development only?

Build the origin list from an environment variable, and include http://localhost:5173 (or your dev port) only in your development .env, as in the function example in Step 3.

Conclusion

To enable CORS in Express, install cors and add app.use(cors()) before your routes. In production, pass an origin list (or function), add credentials: true for cookies, and expose any custom headers your frontend reads. Mount the middleware with app.use() so preflight requests are handled, and on Express 5 drop app.options('*', cors()) or rewrite it as '/{*splat}'.

Related guides:

Rahul

Rahul Kumar is the founder and chief editor of TecAdmin.net. A Red Hat Certified Engineer (RHCE), he has worked in IT since 2009, with hands-on experience in Linux system administration, DevOps, web hosting, cloud platforms and automation. He started TecAdmin in 2013 to share practical, step-by-step guides, and leads its editorial work with one aim: making technical learning clear and useful for sysadmins, developers and beginners alike.

Leave a Reply

Your email address will not be published. Required fields are marked *


Back to top