I'm using the vhost feature in Express with Node to manage multiple subdomains for my app. The app uses the same session secret and key, and I believe I've used the correct session cookie settings:
cookie: {
path : '/',
domain : '.example.com',
httpOnly : false,
maxAge : 1000*60*60*24*30*12 //one year(ish)
}
I set a session variable on my regular site where the subdomain is undefined e.g. http://example.com like so:
req.session.rep_id = rep._id;
res.redirect('https://' + company.name + '.example.com/');
But when I redirect them to subdomain.example.com the session doesn't have the rep_id key set to anything. It seems like the session is getting reset between subdomains. How do I get around this?
You create subdomains to help organize and navigate to different sections of your main website. Within your main domain, you can have as many subdomains as necessary to get to all of the different pages of your website.
Where is the session data stored? It depends on how you set up the express-session module. All solutions store the session id in a cookie, and keep the data server-side. The client will receive the session id in a cookie, and will send it along with every HTTP request.
There are many alternatives to Express-session and it is likely that you are considering building a custom solution. However, as an alternative to Express-session, we have built a secure, open-source and feature-complete solution called SuperTokens. It is already being used by 100s of developers all.
The express-session middleware stores session data on the server; it only saves the session ID in the cookie itself, not session data. By default, it uses in-memory storage and is not designed for a production environment.
Some thoughts:
Try removing the period from .example.com
. My thought here is that you're trying to set a subdomain-only cookie, while still on the root domain. I have read that cookies set on example.com
will be available on all subdomains, too.
Try not redirecting the user to a subdomain immediately, to first verify that the cookie is working on your root domain. Inspect the response headers from your server, then see whether your browser kept the cookie in the next request. Only when you're sure this is working correctly navigate to the subdomain.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With