1

I am using express-session for managing sessions in my Express+NodeJS backend app. I am using Firebase for authentication and Cloud Run for hosting my server. Based on the documentation of Cloud Run hosting, the only cookie allowed is __session. I got it working only if I explicitly set my cookie in my response when user signs in.

res.setHeader("Set-Cookie", req.session);
res.cookie(
  "__session",
  { something: "something" },
  {
    expires: new Date(Date.now() + 900000),
    httpOnly: true,
    sameSite: "none",
    secure: true,
  }
);
res.setHeader("Cache-Control", "private");

However, what I am trying to achieve is I want to set this __session cookie in my app initialization in index.js and it works locally.

app.use(
  session({
    name: "__session",
    secret: process.env.SECRET_SESSION_KEY,
    resave: false,
    saveUninitialized: true,
    store: sessionStore,
    cookie: {
      maxAge: 1000 * 60 * 60 * 24,
      httpOnly: true,
      sameSite: process.env.NODE_ENV === "development" ? "lax" : "none",
      secure: process.env.NODE_ENV === "development" ? false : true,
    },
  })
);

However, in my production app, the cookie is not being set in response headers and cookie storage. In theory, I am setting the cookie name to be __session, but for some reason Firestore/Cloud Run strips it off. What am I doing wrong? Any help is appreciated, my third day trying to solve the issues.

Rogelio Monter
  • 1,084
  • 7
  • 18
Elvin Jafali
  • 113
  • 2
  • 13

1 Answers1

0

I’m not sure if you followed this guide, but there are some important points that could help you. I would suggest reading it and trying to add the endpoints, the HTTPS, and the middleware. Regarding the __session cookie, as described here, you can try several troubleshooting paths. I would give it a read and see if any of those cases is the cause, since I am not able to see any of these in the code you have passed. The cause of it working locally is that cache is not factoring. Another possible cause is that the index is being initialized before the user logs in.

You can also give this code a try and see if it works:

// functions/index.js
const functions = require('firebase-functions');

exports.cookie = functions.https.onRequest((req, res) => {
  if (req.path === '/cookie') {
    res.set({
      'Set-Cookie': '__session=testtesttest; Max-Age=600',
      'Cache-Control': 'private'
    });
    res.send('set cookie');
  } else if (req.method === 'GET') {
    res.send(req.headers.cookie);
  }
});

//firebase.json
{
  "hosting": {
    "rewrites": [
      {"source": "**", "function": "cookie"}
    ],
    "public": "public"
  }
}
Alex
  • 778
  • 1
  • 15