Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Session cookie won't be set due to domain name mis-match, despite explicit naming

I'm having issues understanding why my (session) cookie won't be set client-side. The error appearing on the devtools is the following:

This attempt to set a cookie via Set-Cookie header was blocked because its Domain attribute was invalid with regards to the current host url.

enter image description here

I did a bit of researching, turns out it's a domain issue since both frontend (Firebase) and backend (Cloud run) are on different domain names.

What disturbs me, is that this issue doesn't arrive when my frontend is running on localhost (even though the backend still is remote, on cloud run).

Here's the way I configured my session:

  app.set('trust proxy', 1);
  app.use(json());
  app.use(
    session({
      name: '__session',
      store: new RedisStore({ client: redisClient }),
      secret: options.sessionSecret,
      resave: false,
      saveUninitialized: false,
      cookie: {
        secure: process.env.NODE_ENV === 'PROD' ? true : 'auto',
        httpOnly: true,
        maxAge: 1000 * 60 * 60 * 24 * 7,
        sameSite: process.env.NODE_ENV === 'PROD' ? 'none' : 'lax',
        domain: '<FRONTEND_URL>',
      },
    })
  );

I feel like the domain property is incorrect, yet I provided the frontend domain, the backend domain and the backend's root domain (run.app)

Am I missing something here? Or maybe misunderstanding something?

EDIT: enter image description here As you can see, Secure; SameSite=None is provided in the cookie.

like image 742
Fares Avatar asked Sep 04 '25 01:09

Fares


1 Answers

run.app and a.run.app cannot be used as they are included in the Mozilla Foundation’s Public Suffix List. There is a great article about this issue on Heroku documentation.

To fix this issue, you can:

  1. Set custom domains on your apps. Something like client.example.com and api.example.com.
  2. Deploy both client and API in one Cloud Run instance.
  3. Use a different authentication strategy such as token authentication. Client exchanges credentials against a token and stores it in browser local storage. Client then sends token on every request.

Hope it helps!

like image 61
Jimmy Oliger Avatar answered Sep 07 '25 11:09

Jimmy Oliger