Help with express-session middleware

Hello everyone!

I need some help with express-session. It seems it doesn’t save cookies for routs.

I save cookies on the first route and try to use it on another route, but get undefined. I logged it to the console. It seems like that:

.
Here is my code at app.js:

var session = require('express-session');
const MongoStore = require('connect-mongo')(session);
const path = require('path');
var cookieParser = require('cookie-parser');

app.use(cookieParser());
app.use(session({
  secret: 'keyboard cat',
  resave:true,
  resave: false,
  saveUninitialized: true,
  store: new MongoStore({
    url: 'mongodb://localhost/dictionary'
  })
}));

login.js:

else {
                    req.session.username = username;
                    console.log('cookie at login: ', req.session);
                    res.json(username);
                    //res.json(req.session.username)
                }

home.js:

.get((req, res) => {
        console.log('cookie at home: ', req.session);
     //if (req.session.username) {
      
        fs.readFile('../html/home.html', 'utf8', (err, data) => {
            if (err) console.log(err);
            res.write(data);
            res.end();
        });

What am I doing wrong? I can see the cookie in mongodb, how to use it for different routes?

Can you see the cookie in the browser?

Yes, I see it in the browser and in the mongodb

I noticed that I create 2 types of sessions the first is is without username for /index route and the second with username for /login route. And the app uses the first. How to fix it? A user get the index page first and the app creates a session without username and then uses it. Please help to understand how to fix it.

or I should create one page app? What to use with usual webpages then?

Can you provide a link to your github page so we can set up a dev environment to troubleshoot ?

Here is a link to bitbucket or it should be exactly github? https://bitbucket.org/ostefani/dictionary-app/src/master/
I rewrote a code a little bit. Now I am creating a session on index and try to use it on home route

In order to start a server use index.js in the server folder.

Where are you setting the cookie?

Stock Overflow - Set a cookie in Node.JS

You can use res.cookie() in Express to set your cookies on the browser side.

Sorry @OStefani I’m traveling and won’t have access to my PC till next week and can’t fully troubleshoot.
But looking at your code on my phone I don’t see much difference with my code where I used express-session last time and worked fine,

The only difference maybe that I’m using mongoose , are your sessions being saved to the database? See if there is a collection called sessions for instance. If so then you can eliminate that issue.

If you don’t have it resolved by next week , I’ll take a closer look then. Also if you don’t need to save the session info in a db I recommend you take a look at the more light weight version of saving cookie info for a client called cookie-session, it doesn’t need a db and much easier to use , you just set the time expiry of the cookie and you are good to go. Best of luck

1 Like

Dereje1 Thanks for your reply. Yes I am using mongodb for saving sessions. And after I do a request to index and then to home route I see two documents there. One is without username and one is with username. But the second session is not used. How to use it if it presents in db?

s_coder I am using express session middleware and mongodb

What do you get when you console.log req.session inside your index.js file in your terminal, for any route ?

Actually go to your home route here
https://bitbucket.org/ostefani/dictionary-app/src/e926fd929cde68db650290aa0a375c461f2b7554/routes/home.js?at=master&fileviewer=file-view-default

And console.log req.session in the root route , is it defined ?

Dereje My root route is index. The user got to the index first, signin and then get home

The first session is used for /home route it ‘doesn’t know’ about the username

Could you post the result you get when you do console.log(req.session) In the route I asked you for earlier ?

I’ve post a screenshot, do you see it?

Let me copy and past that text here, maybe you didn’t get the screenshot

Server running at http://127.0.0.1:3000
Get request to index:  Session {
  cookie: 
   { path: '/',
     _expires: null,
     originalMaxAge: null,
     httpOnly: true } }
Post reques to index:  Session {
  cookie: 
   { path: '/',
     _expires: null,
     originalMaxAge: null,
     httpOnly: true },
  username: 'test1' }
Get request to home:  Session {
  cookie: 
   { path: '/',
     _expires: null,
     originalMaxAge: null,
     httpOnly: true } }

Also I’ve consoled log sessions from the index.js which is in the server folder
I got

Server running at http://127.0.0.1:3000
From index file Session {
  cookie: 
   { path: '/',
     _expires: null,
     originalMaxAge: null,
     httpOnly: true } }
From index file Session {
  cookie: 
   { path: '/',
     _expires: null,
     originalMaxAge: null,
     httpOnly: true } }
From index file Session {
  cookie: 
   { path: '/',
     _expires: null,
     originalMaxAge: null,
     httpOnly: true } }

There isn’t any username at all

Ok , what do you get for req.session when the user is not logged in for the same route?

Ok, try instead of this

req.session.username = username;

Use this

req.session.cookie.username = username;

Does that fix your issue?