Skip to content Skip to sidebar Skip to footer

React Production And Cookie Problems

I developed a react app and a express API. Everything were working correctly in localhost. I moved my API to digitalocean droplet which is only IP address and it's HTTP. When I use

Solution 1:

I had faced a similar issue a few months ago. Here's how I solved it.

After running npm build and serving the production build locally, you must have noticed that It stops accepting cookies.

While building my app, I also had this exact issue on local. As I was working on a hobby project I decided to deploy my express-API-server to Heroku and my react-redux client on Netlify to check. (Note: Never push to production without adequate testing.)

Using the "edit this cookie" extension (can be also viewed using browser dev tools ), I found my cookies created at the API server domain, also the API server doesn't send over the cookies to my client. After a lot of research, I didn't get a concrete solution to why this issue persists.

Generally, I saw use credentials: true which seems to solve the issue in most cases (Where I saw no information regarding deployment/production enviornments) but It didn't seem to work for me however, I got some insights.

I decided to use a different approach to solve this. (JWTs)

My insights,

  1. Check your domain and sameSite cookie options, if you're accessing from a client at another domain. (Here, I'm assuming you want to deploy your client somewhere else)
  • You have to set sameSite:false for setting cookies at another domain.
  1. If you're making a SPA, why not bundle the client together with the express server? So this solves the CORS and cookie domain issues.

    const express = require('express');
     const path = require('path');
     const app = express();
    
     app.use(express.static(path.join(__dirname, 'build')));
    
     app.get('/', function (req, res) {
       res.sendFile(path.join(__dirname, 'build', 'index.html'));
     });
    
     app.listen(9000);
    
  2. Use Token-based sessions (JWT)

  • Agreed not ideal in every situation, but it helps for most scenarios.

I have built a few MERN-based apps, most deployed. Refer those to see how JWT is implemented in MERN.

  1. https://stackoverflow.com/a/53566745/12408623

References

  1. https://create-react-app.dev/docs/deployment/
  2. https://stackoverflow.com/a/53566745/12408623

Post a Comment for "React Production And Cookie Problems"