A better way to use cors in Node with Express

Adel Benyahia
2 min readDec 24, 2022

In this tutorial we will use cors npm package as middleware with Node application with express

Photo by Sergey Zolkin on Unsplash

Cross-Origin Resource Sharing (CORS)

Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources. CORS also relies on a mechanism by which browsers make a “preflight” request to the server hosting the cross-origin resource, in order to check that the server will permit the actual request. In that preflight, the browser sends headers that indicate the HTTP method and headers that will be used in the actual request.

CORS is a node.js package for providing a Connect/Express middleware that can be used to enable CORS with various options.

Why this article

In most article in the internet, the cors package is used with the default options.

This work if the web application front-end and back-end are in the same origin (same IP address) and the same PORT, else the application will crash with cors origin error.

In most web applications, the front-end and back-end will be in different servers with different IPs

Or in the same server with different ports

To fix that we will use a custom options for our cors npm package

1. create a new file: “config/allowedOrigins.js”

This file will contain a list of all allowed origins IPs

const allowedOrigins = [
'http://localhost:3000',
'http://127.0.0.1:3000',
'https://www.yourwebsite.com', //front-end website
]
module.exports = allowedOrigins

2. create a new file: “config/corsConfigs.js”

this file will contain the cors package configuration options

const allowedOrigins = require('./allowedOrigins')
const corsConfigs = {
origin: (origin, callback) => {
if (allowedOrigins.indexOf(origin) !== -1 || !origin) {
// remove ||!origin to block postman request
callback(null, true)
} else {
callback(new Error('origin not allowed by Cors'))
}
},
optionsSuccessStatus: 200,
}
module.exports = corsConfigs
  • if the “origin” exist in our allowedOrigins then we return a callback function with (null, true) where “null” represent null error, and “true” represent a successful allowed origin
  • “|| !origin”: if the request don’t have an origin ( like postman request), this must only be allowed in development mode
  • Else we throw an error with the message: ‘origin not allowed by Cors’

3. Call the cors package with “corsConfigs” as parameters

const corsConfigs = require('./config/corsConfigs')

....

app.use(cors(corsConfigs))

--

--

Adel Benyahia

Web application developer (HTML │ CSS │ JS | ReactJS | NextJS | NestJS | MERN)