CORS with Express

Updated: 03 September 2023

There are two parts to making a response, the request and the response

We need to handle CORS on each end

Browser

In the browser, we can make cross-origin requests using fetch with mode:no-cors which will make an opaque response which has some limitations

1
var res = await fetch('https://my-other-url.com/hello-world', {
2
mode: 'use-cors',
3
})
4
console.log(res) //  {type: "opaque", url: "", redirected: false, status: 0, ok: false, …}

Now, sure that’s great and all when using a 3rd party API, however as mentioned there are limitations to the response object that is received. We can compare this to a API that has CORS enabled

1
var res = await fetch('https://my-other-url.com/hello-world')
2
console.log(res) // {type: "basic", url: "https://my-other-url.com/hello-world/", redirected: false, status: 200, ok: true, …}

Note that this response has a lot more data included

Node.js

When using express we simply need to set the response header to enable CORS. We can do this using a simple middlewear, in this case a simple function which takes in an array of origins (or even a single origin) and returns a cors middlewear function

cors.js

1
const useCors = (origins = '*') => {
2
const cors = (req, res, next) => {
3
res.set('Access-Control-Allow-Origin', origins)
4
next()
5
}
6
7
return cors
8
}
9
10
module.exports = useCors

In our main express file we can use this in one of two ways

We can either choose to allow all origins by default *

server.js

1
const express = require('express')
2
const app = express()
3
4
const cors = require('./cors.js')
5
6
app.use(cors())
7
8
// ... normal express stuff

Or only allow specific origins:

1
const express = require('express')
2
const app = express()
3
4
const cors = require('./cors.js')
5
6
app.use(cors(['*.my-website.com', '*.glitch.com']))
7
8
// ... normal express stuff