0

I'm a little confused about how to handle cookies between frontend and backend.

I have a

  1. frontend react application
  2. a backend node express application.

The frontend is hosted on Netlify and the backend on Heroku.

It seems that you cannot put these apps on the same domain- www.mydomain.com (not sure if correct). So instead I have them on different subdomains: the frontend Netlify app on staging.mydomain.com and the Heroku backend on api.mydomain.com.

But I need api.mydomain.com to send a locale cookie to frontend which needs to be read by javascript of the frontend app. But it seems it's not possible to set a cookie from one domain onto another- like api.mydomain.com to set a cookie on staging.mydomain.com (not sure if correct). And it seems if the cookie is on a different domain like api.mydomain.com, it cannot be read by javascript by the frontend app on the other domain staging.mydomain.com (not sure if correct).

It seems like sending cookies from a backend to frontend in order to be read by javascript would be a common behavior, so I feel I'm missing some information. Is it incorrect to have your backend and frontend on different subdomains? It didn't look like it was an option to put them on the same domain with heroku and netlify, so it seemed to me putting your backend and frontend on different subdomains was the only or atleast more common way to go. How do you handle your backend sending cookies to the frontend?

1

I was wrong that you couldn't set cookies between subdomains. Setting the domain on the set cookie header to mydomain.com solved the issue.

    res.cookie('locale', JSON.stringify(localeObj), {
      maxAge: new Date() * 0.001 + 300,
      domain: 'mydomain.com',
      secure: true,
      sameSite:'none',
    });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.