My application is using ReactJs for frontend and NodeJs + Express for backend API. Everything seem to be fine until I use express-session for application session.
Google Cloud Function is a very good cloud based service for hosting. You can easily deploy your NodeJs app into this platform. But when it is used along with express-session there is a problem. When client send a request to server, the response is returned flawlessly but session id cannot be saved into client cookie. Therefore, all later requests the server treats as from new session.
I was spending hours to find out the solution for this. Some say that when you initialize the session in express app, you have to set cookie secure option to false for non-https. Or in the client side, for every request you have to set credential = “include” option for whatever Ajax calls using ES6 fetch or Axios. Unfortunately all tries with those ways would not be working.
By the design of Google Cloud Function, __session is the only cookie that you can store. This is necessary for them to be able to efficiently cache content on the CDN. And you have to set Cache-Control Header as private, this is also important.
So in the express application, you many create a session config with the name ‘__session’ as below to get it work
Don’t forget to set Cache-Control Header as private
So after your first request to server, a cookie for session id with name ‘__session‘ should be stored in your browser cookie.
Your cookie for the session is stored correctly on your browser. Now you have to set proper credential option in your request to get the cookie information sent with the request to server side.
You can learn more about request credentials here
All done, your session is now maintained in the server.