Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save afterburn/4944df2782f00023f17122e3fa074c4c to your computer and use it in GitHub Desktop.
Save afterburn/4944df2782f00023f17122e3fa074c4c to your computer and use it in GitHub Desktop.
Checklist for making sessions persist cross-domain using Express & MongoDB

Checklist for making sessions persist cross-domain using Express & MongoDB

  1. Enable withCredentials and crossDomain if you make AJAX requests to your API with jQuery.

Note - Make sure you change your AJAX setup before any AJAX requests are executed or this will silently fail.

$.ajaxSetup({
	xhrFields: { withCredentials: true },
	crossDomain: true
});
  1. Make sure your requests made to your Express app have the appropriate headers.
function middleware(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,OPTIONS");
	res.header("Access-Control-Allow-Headers", "X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept");
	next();
}
  1. Make sure you´ve configured express-session correctly:
this.app.use(session({
	resave: false,
	saveUninitialized: false,
	secret: config.secret,
	store: new MongoStore({ mongooseConnection: this.database.connection, autoReconnect: true }),
	cookie: {
		path: '/',
		httpOnly: true,
		domain: '.ENTERDOMAIN.HERE',
		maxAge: 24 * 6 * 60 * 10000 
	}
}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment