Home > other >  React/Express set-cookie not working across different subdomains
React/Express set-cookie not working across different subdomains

Time:12-24

I have a React frontend with Express API server, and I am trying to store a JWT in a secure httpOnly cookie for authorization. Below are the relevant parts of my code, which includes everything I've tried from countless Google/StackOverflow searches.

Am I missing something simple? I am trying to avoid storing the JWT in localStorage, but I am just at a loss right now. Nothing seems to work.

API (https://api.mydomain.com):

app.use(cors({
  credentials: true,
  exposedHeaders: ['SET-COOKIE'],
  origin: 'https://staging.mydomain.com',
}));

app.post('/auth/login', (request, response) => {
  ...

  response.cookie('jwt', JWT.sign({ id: user.id }, ...), {
    domain: 'mydomain.com',
    httpOnly: true,
    sameSite: 'none',
    secure: true,
  });

  response.json(user);
});

Web (https://staging.mydomain.com):

await fetch('https://api.mydomain.com/auth/login', {
  body: JSON.stringify({ ... }),
  credentials: 'include',
  headers: {
    'Content-Type': 'application/json',
  },
  method: 'POST',
});

I see the set-cookie header in the response, but I do not see the cookie set in the developer tools and it is not passed in subsequent API requests.

Response Headers:
access-control-allow-credentials: true
access-control-allow-origin: https://staging.mydomain.com
access-control-expose-headers: SET-COOKIE
set-cookie: jwt=abcde*********.abcde*********.abcde*********; Domain=mydomain.com; Path=/; HttpOnly; Secure; SameSite=None

CodePudding user response:

On your server, when you are setting the cookie, can you try adding a dot before the domain. The leading dot implies that the cookie is valid for subdomains as well.

response.cookie('jwt', JWT.sign({ id: user.id }, ...), {
  domain: '.mydomain.com',
  httpOnly: true,
  sameSite: 'none',
  secure: true,
});

When the client (here, https://staging.mydomain.com) will receive the Set-Cookie response header, with the trailing dot domain, it would accept the cookie since now the cookie is valid for subdomains too.

On a side note, I find Cookie Editor really helpful for debugging cookies.

Hope this answer helps you! :)

  • Related