express CORS Middleware


This example demonstrates how a cross origin http request can be handled using a middleware.

CORS Background

CORS is an access control method adopted by all major browsers to avert Cross Scripting Vulnerabilities inherent by them. In general browser security, scripts should maintain that all XHR requests has to be made only to the source the same scripts are served from. If an XHR request is made outside the domain the scripts are belonging to, the response will be rejected.

However if the browser supports CORS, it would make an exception to this rule if appropriate headers in the response indicate that the domain which the request is originated from is allowed. The following header indicates that any domain is allowed:

Access-Control-Allow-Origin: *


Following example shows how Express middleware can include these headers in it's response.

app.use(function(request, response, next){

    response.header('Access-Control-Allow-Origin', '*');
    response.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    response.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');

   //Handle Preflight 
   if (reqest.method === 'OPTIONS') {
   else {


Handling Preflight

The latter part of the above example handles Preflight. Preflight is a special OPTIONS request the browser send to test CORS if the request contain custom headers.

Useful References

MDN - CORS Http Tutorial