Auth session cookie is missing on express react app

By: Niraj Dhungana

Aug 1 2022

#react#express

Share:

If you are working on the express and react app and got stuck on the authentication part. Then this post is going to help you with that.

Recently I was working on the React and Express project where I needed an authentication system. I choose to go for auth with passport js and session cookies.

While I was testing with Postman everything was fine but once I connected everything the react app was not working the way Postman does. It took me almost all day to figure out what exactly is the problem.

But the solution was already presented in the browser itself. And obviously, the problem was happening because I was trying to access the Express app from the React app which both were running on different Ports.

The secret error from the express session

As we already know every browser has a console and if you got any error you will see those red unknowing error messages inside those console windows. But this time when it comes to express sessions you will not get any error inside your backend or inside your React app.

But if you see very carefully as I mentioned in this image. You will see this little warning or error whatever you want to call it if you expand it there you can read what exactly is causing the problem.

secret error messege for auth session

If you click on that warning and expand it you will also see the solution that you need to apply.

solution for react and express session auth

Inside your backend where you are setting up your cookie session, you have to add lax for sameSite option.

1app.use(
2  session({
3    secret: process.env.SESSION_SECRET,
4    resave: false,
5    saveUninitialized: false,
6    cookie: {
7      sameSite: "lax", // if we don't set this the browser will complain
8    },
9  })
10);
11

And that's it you can now try by sending auth request again. I could have told you the solution earlier which I didn't and that is because now you know the new debugging technique.

author

Niraj Dhungana

I hope you enjoyed reading this post and learned something new. If not then tell me how can I improve. @fsniraj