Home > Blockchain >  Express-Session working fine on REST-client (VS Studio extension) but not in React site
Express-Session working fine on REST-client (VS Studio extension) but not in React site

Time:11-26

Basically, if I declare a session variable on one route, I can't access it (undefined) in another one.

This is my middleware:

app.use(cors({
 origin: ["http://localhost:3000"], methods: ["GET", "POST"] })); 
app.use(session({ 
 secret: process.env.SESSION_SECRET, 
 resave: false, saveUninitialized: false 
 }));

And this is my /log-in route:

router.post('/api/users/auth/log-in/', async (req, res) => {
 // ... user authentication logic, here 'authenticated' boolean is defined 
 req.session.authenticated = authenticated; 
 req.session.save(); 
 if (authenticated) req.session.user = req.body.username; 
 res.json({"success": true, "authenticated": authenticated}); 
});

If I log the session variable inside this route, It works just fine.

But then, in another route, when accessing with req.session.authenticated, the variable returns an undefined.

I'm sure there's something I'm missing but I can't make it work. Any help is appreciated!

To clarify, If I do all this (logging in and checking if I'm authenticated) from REST client, it works fine.

CodePudding user response:

If it works fine via your REST client and not via the app, it probably means the cookie is not being sent. Have you checked the requests int the developer tools network tab?

Just a small note on your code:

// this has no impact because after this route completes, req is destroyed. 
// It is the express-session middleware that will pickup the cookie 
// and populate the req.session object for incoming each request.
if (authenticated) req.session.user = req.body.username; 

CodePudding user response:

Turns out I was missing the credentials handling on each fetch, so the cookie wasn't been sent

Adding credentials: 'include' to every fetch request solved it.

  • Related