How to share cookies through ports / domains using Express

I have two node.js (express) applications running on two different ports. One runs on localhost:3000 , and the other runs on localhost:4000 . An application on port 3000 has the following cookie configuration:

 app.use(express.cookieParser()) app.use(express.session({ key: settings.session.key, secret: settings.session.secret, cookie: settings.session.cookie, fingerprint: function () { return '' }, store: new MemoryStore() })) 

And another application (on port 4000 ) has:

 app.use(express.cookieParser()) app.use(express.session({ key: settings.session.key, secret: settings.session.secret, cookie: settings.session.cookie, fingerprint: function() { return '' }, store: new MongoSessionStore({ db: db }) })) 

They both use the same session configuration object (the only difference is that one is stored in MongoDB and the other in memory.

I set this cookie localhost:3000 :

 res.cookie('mycookie', 'bar', { domain: 'localhost:4000' }) 

And then I POST (with jquery.ajax) to the route on localhost:4000 , but mycookie does not.

Note. I have CORS configured on localhost:4000 to accept the start of localhost:3000 , and when I post to jQuery, I use xhrFields: { withCredentials: true } .

So my question is how to properly configure applications to set cookies on each other? :)

+4
source share
1 answer

I suggest you share a session repository between both applications.

Edit: just to clarify, you cannot set cookies from one domain to another. Therefore, domainA cannot set a cookie for domainB - you must get domainB to set a cookie (for example, by visiting domainB ). Using the current configuration, you should be able to read cookies as expected.

Initially, I thought you wanted to split the state between two applications via cookies, so I suggested sharing session storage between applications.
+1
source

Source: https://habr.com/ru/post/1501719/


All Articles