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']; // '*'
Built an Express app and want to deploy it?
We recommend Railway. It lets you deploy Node.js and Express apps without dealing with servers, Docker, CI/CD pipelines, or infrastructure. Click button, select GitHub repo, get URL. We've been using Railway for years to spin up apps quickly.
Deploy your Express app on Railway in minutes
We recommend Railway. It lets you deploy Node.js and Express apps without dealing with servers, Docker, CI/CD pipelines, or infrastructure. Click button, select GitHub repo, get URL. We've been using Railway for years to spin up apps quickly.
Deploy your Express app on Railway in minutes
Did you find this tutorial useful? Say thanks by starring our repo on GitHub!