Fastify cookie setup not working from subdomain

299 views Asked by At

I've scoured the internet for a while, but haven't been able to find out what I might be doing wrong. I've a fastify server which is hosted on a subdomain: https://api.example.com

The UI is served via CloudFlare pages on the domain https://example.com and it's a react-app.

Now I am calling the /authenticate endpoint in my backend via the fetch in the UI as:

 const requestOptions: RequestInit = {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      redirect: "follow",
      referrerPolicy: "no-referrer",
      body: JSON.stringify({ message })
    };

return fetch(`${SERVER_URI}/authenticate`, requestOptions)
  .then(response => response.json())
  .then(result => console.log({ result }));

On the backend I am using the following setup:

 // Setup the CORS package
 await fastify.register(require('@fastify/cors'), {
    origin: /example\.com$/,
    methods: ['GET', 'PUT', 'POST', 'DELETE']
  });


// Cookies Manager
fastify.register(require('@fastify/cookie'), {
    secret: 'someSecret'
});

When the /authenticate endpoint is called, it goes to a method which should set the cookie in the browser by running the following code:

AuthController.js:
...

res
  .setCookie('__auth', token, {
    domain: '.example.com',
    path: '/',
    signed: true,
    httpOnly: true,
    secure: true,
    sameSite: 'Lax'
  })
  .send({ authenticated: true, meta: {} });
  • I tried to add credentials: 'include' in the fetch call from the UI, that didn't help.
  • I read about the different properties and headers that are available, but I am definitely missing something which has lead me to stackoverflow.

Expectation:

  • Cookie to be set in the browser.
0

There are 0 answers