0

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.
johnhogl8
  • 1
  • 1
  • `/example\.com$/` is insecure, since it also matches Web origins like `https://notexample.com`. – jub0bs Jun 08 '23 at 06:23
  • You write: _I tried to add `credentials: 'include'` in the fetch call from the UI, that didn't help._ That is a necessary condition for the cookie to get set, though. You will also need to allow credentials in your CORS configuration. – jub0bs Jun 08 '23 at 18:08

0 Answers0