Managing CORS in Express – Allow Cross Origin Requests

By Digamber Rawat Last updated on
Learn to enable CORS in Express or Node server for enabling cross-site requests. CORS refers to cross-origin request sharing. In this tutorial, we will look at how to manage CORS in Express.js. Along with that, we will check out the custom header types and how to set HTTP cookies.

A web or mobile application can access HTTP resources from the same origin it is being served. To access the resources (images, stylesheets, scripts, iframes, and videos.) from the other domains or origin, this mechanism is known as CORS.

CORS is a security policy, and it protects you from harmful and vicious users. Those wicked users can ruin your platform.

CORS must be added to the server for both securing resources, and if it is not added then, all the third party requests will be failed, and resources won’t be fetched.

Here are the reasons for CORS error:

  • Request from another domain
  • Request from an unknown port
  • Request from another subdomain
  • Request from different protocol

If you are willing to solve CORS issue in Angular then you should check out: Solving CORS Issue in Angular 8/9 with Proxy Configuration.

Enabling CORS in Express

Install cors npm package in Express and Node app.

npm install cors --save

Import express npm package and use cors as a middleware in a node server. That is how we can enable the CORS in an Express.

// server.js or app.js

const express = require('express');
const cors = require('cors');
const app = express();

app.use(cors());

Configure CORS in Express for All Resources

Express middlewares are helpful for setting up CORS. The Access-Control-Allow-Origin header allows cross origin request and * wildcard denotes allowing access any origin

res.header("Access-Control-Allow-Origin", "*");

This below express function is allowing CORS for all resources on your server.

// server.js or app.js

const express = require('express');
const cors = require('cors');
const app = express();

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

Restrict Specific Host

We can also restrict specific host using the origin option in the express.

app.use(cors({
  origin: 'http://xyz.com'
}));

We can also restrict the origin list rather than a single string in the origin property.

const express = require('express')
const cors = require('cors')
const app = express()

let whitelist = ['http://localhost:4000', 'http://abc.com']

app.use(cors({
  origin: function(origin, callback){
    // allow requests with no origin 
    if(!origin) return callback(null, true);
    if(whitelist.indexOf(origin) === -1){
      var message = 'The CORS policy for this origin doesn't ' +
                'allow access from the particular origin.';
      return callback(new Error(message), false);
    }
    return callback(null, true);
  }
}));

The domain name which made the request will return the following header

Access-Control-Allow-Origin: http://localhost:4000

Custom Header Types

We can set 6 types of response headers with cross-origin request sharing, here is the list of header types:

Header Details
Cache-Control The Cache-Control general-header scope is used to define directives for caching mechanisms in both requests and responses.
Content-Language The Content-Language entity-header is used to specify the language(s) designated for the audience so that it provides a user to differentiate according to the users’ own adopted language.
Cache-Type The Content-Type entity-header is used to symbolize the media type of the resource.
Expires – HTTP The Expires header comprises the date/time after which the response is considered spoiled.
Last-Modified The Last-Modified response HTTP header includes the date and time at which the origin server considers the resource was last changed.
Pragma The Pragma HTTP/1.0 general-header is an implementation-specific header that may have several conclusions along the request-response chain.

Use exposedHeaders property in express middleware to expose headers.

app.use(cors({
 exposedHeaders: ['Content-Length', 'A-BCD', 'Z-XYZ'],
}));

Setting HTTP Cookies with CORS

To configure HTTP session over CORS is easy since the HTTP session are dependent on cookies. So we need to follow the two steps to enable the HTTP cookies in response to CORS.

1: First set the credentials: true in the express middleware function. It will add and Access-Control-Allow-Credentials header.

const express = require('express')
const cors = require('cors')
const app = express()

app.use(cors({
  credentials: true,
}));

2: Then, you must set withCredentials to true when you intend to call an AJAX request.

var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://abc.com/', true);
xhr.withCredentials = true;
xhr.send(null);

Conclusion

Finally, we have completed express tutorial in which we learned how to enable CORS and HTTP cookies in node and express server.

Digamber Rawat
Digamber Rawat

Full stack developer with a passion for UI/UX design. I create beautiful and useful digital products to solve people’s problem and make their life easy.