Cross-origin resource sharing (CORS) allows AJAX requests to skip the Same-origin policy and access resources from remote hosts.
In this post I will show you how to enable CORS support in Express. I will also provide some tips to handle common use cases that come up when working with Single Page Applications, like exposing HTTP sessions and custom headers.
Enabling CORS
The easiest way to get CORS working in Express is by using the cors npm module.
You can simply add it as a dependency:
npm install –save cors
And then use it as middleware:
var express = require(‘express’);var cors = require(‘cors’);var app = express();app.use(cors());/* your regular routes go here */
That?s it. CORS is now enabled.
If you make a request to your app, you will notice a new header being returned:
Access-Control-Allow-Origin: *
The Access-Control-Allow-Origin header determines which origins are allowed to access server resources over CORS (the * wildcard allows access from any origin).
Restricting allowed hosts
If you want to restrict AJAX access to a single origin, you can use the origin option:
app.use(cors({ origin: ‘http://yourapp.com’}));
If you would rather have a list of allowed origins, you can use a function instead of a string as the origin value:
var allowedOrigins = [‘http://localhost:3000’, ‘http://yourapp.com’];app.use(cors({ origin: function(origin, callback){ // allow requests with no origin // (like mobile apps or curl requests) if(!origin) return callback(null, true); if(allowedOrigins.indexOf(origin) === -1){ var msg = ‘The CORS policy for this site does not ‘ + ‘allow access from the specified Origin.’; return callback(new Error(msg), false); } return callback(null, true); }}));
If you make a new request to the server, you will notice the Access-Control-Allow-Origin header now returns the value of the origin making the request:
Access-Control-Allow-Origin: http://localhost:3000
Sending custom headers
By default, only 6 response headers are exposed over CORS:
- Cache-Control
- Content-Language
- Content-Type
- Expires
- Last-Modified
- Pragma
If you want to expose other headers, you can use the exposedHeaders option:
app.use(cors({ exposedHeaders: [‘Content-Length’, ‘X-Foo’, ‘X-Bar’],}));
You will notice your server responses now include an additional Access-Control-Expose-Headers header:
Access-Control-Expose-Headers: Content-Length,X-Foo,X-Bar
HTTP Sessions Over CORS
HTTP sessions are a tried and true mechanism to deal with authentication on the web. However, HTTP Sessions rely on cookies, which are not sent by default over CORS.
To enable HTTP cookies over CORS, we need to follow two steps:
- Set the credentials options to true.
app.use(cors({ credentials: true,}));
This will make the response include an additional Access-Control-Allow-Credentials header:
Access-Control-Allow-Credentials: true
2. When making the AJAX request, make sure to set the withCredentials property to true.
var xhr = new XMLHttpRequest();xhr.open(‘GET’, ‘http://example.com/’, true);xhr.withCredentials = true;xhr.send(null);
Conclusion
Adding CORS support in Express is fast and easy, especially if we use the cors library.
** Note: you can find an example express app with CORS support here.