Node.js: enable CORS

In this article we will see how to enable CORS in Node.js.

We simply need to add two additional HTTP headers to every request or to a set of specific requests processed by our application. The two required headers are Access-Control-Allow-Origin and Access-Control-Allow-Headers that can be set as follows:


'use strict';

const https = require('https');

const fs = require('fs');

const PORT = process.env.PORT || 8000;

const options = {
  key: fs.readFileSync('key.pem'),
  cert: fs.readFileSync('cert.pem')
};

https.createServer(options, (req, res) => {
  res.writeHead(200, {
      'Content-Type': 'application/json',
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept'
  });
  res.end(JSON.stringify({
     version: '1.0',
     endpoint: req.url,
     method: req.method,
     headers: req.headers 
  }, null, 2));
}).listen(PORT);

In the above example, all of the endpoints of our sample application have CORS enabled so that we can write a simple test on the client side:


(function() {
    fetch('https://api.tld/test')
    .then(response => response.json())
    .then(data => console.log(data));
})();   

In a typical ExpressJS we can create a middleware to enable CORS only on a specific router's instance:


router.use((req, res, next) => {
    res.set('Access-Control-Allow-Origin','*');
    res.set('Access-Control-Allow-Headers','Origin, X-Requested-With, Content-Type, Accept');
    next();
});

By doing so, we can actually enable CORS only on a specific group of routes.

Back to top