How to handle CORS in Express JS

Updated: December 28, 2023 By: Guest Contributor Post a comment

Overview

Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell browsers to give a web application running at one origin, access to selected resources from a different origin. A web application executes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, or port) from its own.

CORS errors are common in modern web development when a server does not include the proper headers to allow the frontend application hosted on a different domain to access the resources. Understanding and handling CORS in your Express.js application is crucial for allowing your API to be accessible to different clients securely.

CORS in Express JS

To handle CORS in Express.js, you will typically use a middleware named ‘cors’. This package provides a Connect/Express middleware that can be used to enable CORS with various options.

First, you need to install the cors middleware:

npm install cors

Then, include it in your Express app to enable CORS on all routes:

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

const app = express();

app.use(cors());

// your routes go here

To enable CORS for a single route:

app.get('/my-route', cors(), (req, res) => {
  res.json({ msg: 'This route has CORS enabled' });
});

You can also configure CORS to include more security, by including options like ‘origin’, ‘methods’, and others:

var corsOptions = {
  origin: 'http://example.com',
  optionsSuccessStatus: 200
};

app.use(cors(corsOptions));

Complete Code Example

Here is a complete example of a basic Express.js server setup with CORS enabled for all routes:

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

const app = express();

app.use(cors());

app.get('/', (req, res) => {
  res.send('CORS-enabled for all origins!');
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

Advanced Example

For more fine-grained control, you can set CORS on a per-route basis and with specific rules. Here’s how you might allow only GET requests from a specific origin and credentialed requests:

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

const allowedOrigins = ['http://example1.com', 'http://example2.com'];

const corsOptionsDelegate = function (req, callback) {
  var corsOptions;
  if (allowedOrigins.indexOf(req.header('Origin')) !== -1) {
    corsOptions = { origin: true }; // reflect (enable) the requested origin in the CORS response
  } else {
    corsOptions = { origin: false }; // disable CORS for this request
  }
  callback(null, corsOptions); // callback expects two parameters: error and options
};

app.get('/product/:id', cors(corsOptionsDelegate), (req, res) => {
  // Handle the get for this route
});

app.listen(3000, function () {
  console.log('CORS-enabled web server listening on port 3000');
});

Conclusion

In this tutorial, we have gone through the basics of CORS and how to handle it in Express.js using the ‘cors’ middleware. Starting from a simple usage of enabling CORS across all routes, we traversed through advanced configurations, like setting CORS per-route with specific options and a delegate function for more dynamic scenarios.

Understanding and implementing CORS is crucial for the security and flexibility of your web services. By using the ‘cors’ middleware, you can effectively manage cross-origin requests and ensure that your Express.js APIs are accessible from various client-side applications.

Always remember to only allow trusted origins and to configure your CORS policy as restrictive as needed for your use case to maintain the security of your application.