CORS with Express

Sep 12, 2019

CORS headers allow apps running in the browser to make requests to servers on different domains (also known as origins). CORS headers are set on the server side - the HTTP server is responsible for indicating that a given HTTP request can be cross-origin.

The cors npm module is an Express middleware that sets CORS headers on the Express response object.

const app = require('express')();
// Set CORS headers on all responses
app.use(require('cors')());

app.get('/', (req, res) => res.send('Hello, World!'));
const server = await app.listen(3000);

// Make an example request to see that, yep, the CORS headers are set
const axios = require('axios');
const res = await axios.get('http://localhost:3000');
res.headers['access-control-allow-origin']; // '*'

You can also declare CORS middleware on a certain subset of your routes by passing a string parameter to use().

const app = require('express')();
// Set CORS headers on responses to any requests whose URL starts with
// '/api'
app.use('/api', require('cors')());

app.get('/api/test', (req, res) => res.json({ ok: 1 }));
app.get('/', (req, res) => res.send('Hello, World!'));
const server = await app.listen(3000);

// Make an example request to see that CORS headers are set on
// `/api/test`, but not `/`
const axios = require('axios');
let res = await axios.get('http://localhost:3000');
res.headers['access-control-allow-origin']; // undefined

res = await axios.get('http://localhost:3000/api/test');
res.headers['access-control-allow-origin']; // '*'

Want to become your team's Express expert? There's no better way to really grok a framework than to write your own clone from scratch. In 15 concise pages, this tutorial walks you through how to write a simplified clone of Express called Espresso. Get your copy!

Espresso supports:
  • Route handlers, like `app.get()` and `app.post()`
  • Express-compatible middleware, like `app.use(require('cors')())`
  • Express 4.0 style subrouters
As a bonus, Espresso also supports async functions, unlike Express.

Get the tutorial and master Express today!

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Express Tutorials