Enable CORS in express.js

suggest change

Node.js is often used to build an API. CORS is what lets a browser on another origin call that API.

This example allows any origin and the listed methods. Do not use Access-Control-Allow-Origin: * if the browser sends credentials. Register app.options once, not inside the middleware. Doing it inside app.use adds a new route on every request.

express below is require('express').

const app = express();

app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    // https://developer.mozilla.org/en-US/docs/Glossary/preflight_request
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
    res.header('Access-Control-Allow-Methods', 'GET, PATCH, PUT, POST, DELETE, OPTIONS');
    next();
});

app.options('*', (req, res) => {
    res.sendStatus(204);
});

In production, Node.js often runs behind a proxy. Apache or Nginx can own the CORS headers instead.

To conveniently adapt this scenario, it’s possible to only enable node.js CORS when it’s in development.

This is easily done by checking NODE_ENV:

const app = express();

if (process.env.NODE_ENV === 'development') {
    // CORS settings
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents