Using Express and Node, how to maintain a Session across subdomains/hostheaders

First of all to allow browser to make cross-domain requests you need to set headers on server side. This solution works for normal request as well as AJAX.
In your express configure function:

Express 4.0:

var express = require('express');
var session = require('express-session');
var cookieParser = require('cookie-parser');

var app = express();

app.use(cookieParser());
app.use(session({
    secret: 'yoursecret',
    cookie: {
        path: "https://stackoverflow.com/",
        domain: 'yourdomain.com',
        maxAge: 1000 * 60 * 24 // 24 hours
    }
}));
app.use(function(req, res, next) {
    res.header('Access-Control-Allow-Credentials', true);
    res.header('Access-Control-Allow-Origin', req.headers.origin);
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
    next();
});

Access-Control-Allow-Origin can be set to ‘*’ if no cross-domain cookies exchange for sessions needed.
To have cookies and session shared cross-domain you need to set specific Access-Control-Allow-Origin to actually domain where request is made from, that’s why req.headers.origin – is perfect for that.

Using domain it wont work well on localhost – so make sure you disable it in development environment, and enable on production. It will enable shared cookies across top and sub domains.

This is not all.
Browsers it self won’t send cookies over cross domain requests, and this have to be forced.
In jQuery you can add extra parameter in $.ajax() request:

xhrFields: { withCredentials: true }

For non jQuery, just have XHR constructor and set this parameter:

xhr.withCredentials = true;

And you are ready to do cross-domain with shared session.

Leave a Comment