Cross-Domain Cookie Issues: React Frontend on Netlify and Node.js Backend on Railway

I’m having trouble with cookies in my deployed app. The frontend is on Netlify and the backend on Railway. It works fine locally but not in production.

The main problems are:

  1. Cookies aren’t being set in the browser. I get a message saying it’s blocked due to user preference.
  2. API calls don’t include the cookie.

My setup:

Backend (Express):

app.use(cors({
  origin: process.env.FRONTEND_URL || 'http://localhost:5173',
  credentials: true,
}));

res.cookie('authToken', `Bearer ${generatedToken}`, {
  httpOnly: true,
  secure: process.env.NODE_ENV === 'production',
  maxAge: 7200000,
  sameSite: 'none',
});

Frontend (React with RTK Query):

const apiQuery = fetchBaseQuery({
    baseUrl: import.meta.env.VITE_API_URL,
    credentials: "include",
});

Environment setup:

FRONTEND_URL: https://my-app-frontend.netlify.app
VITE_API_URL: https://my-app-backend.up.railway.app

Login works and creates a token but it’s not sent with other API requests. I get a 401 error even though the token exists. The token disappears on page reload too.

I’ve tried Chrome, Safari, and Edge. They all have the same issue.

Why are cookies being blocked? How can I make sure they work properly in production for cross-origin requests?

hey silvia, sounds like a tricky one! have u checked ur SameSite and Secure settings? sometimes browsers block cookies if they’re not set right for cross-origin stuff. also, make sure ur domains match exactly between frontend and backend. might wanna double-check ur CORS config too. good luck!

hmm, interesting problem! have u tried clearing ur browser cache and cookies? sometimes that helps. also, whats ur exact domain setup? maybe theres a mismatch somewhere? oh, and have u checked if ur SSL certificates are set up correctly on both ends? just brainstorming here - what else have u tried so far?

Cross-domain cookie issues can be frustrating. Have you considered using a custom domain for both your frontend and backend? This approach often resolves cookie-related problems in production environments. Alternatively, you might want to explore using localStorage or sessionStorage for token storage, though this comes with its own security considerations. Ensure your backend is setting the ‘Access-Control-Allow-Credentials’ header to ‘true’ as well. If these don’t work, you may need to implement a more robust authentication strategy, such as JWT with refresh tokens stored in HTTP-only cookies.