Home  >  Q&A  >  body text

req.session.user - Property 'User'; does not exist on type 'Session'; error while trying to pass session data using express session

I'm trying to make a simple login form for users to log into a website and then save their session data into a session cookie. I'm using express-session and in their documentation it gives this as an example of setting it up:

app.post('/login', express.urlencoded({ extended: false }), function (req, res) {
  // login logic to validate req.body.user and req.body.pass
  // would be implemented here. for this example any combo works

    // store user information in session, typically a user id
    req.session.user = req.body.user

    // save the session before redirection to ensure page
    // load does not happen before session is saved
    req.session.save(function (err) {
      if (err) return next(err)
      res.redirect('/')
    })
  })
})

But in my code I keep getting an error in the "req.session.user" section which says: "Property 'user' does not exist on type 'session and section'" , even though I'm using the exact same code from the Express-Session documentation.

I followed all the instructions in the documentation and put this at the top of the program:

import session from 'express-session';

app.set('trust proxy', 1);

app.use(session({  
  name: `First_test`,
  secret: 'secret_text', 
  saveUninitialized: true, 
  resave: true,
  cookie: { 
    secure: false, 
    maxAge: 960000 
  } 
}));

When debugging, I can see that there is indeed no "user" attribute inside req.session.

I've searched google and stackoverflow but didn't find a solution. I'm most likely missing some small steps and I'm hoping someone here can help educate me.

Thank you for your help in advance.

P粉593536104P粉593536104258 days ago373

reply all(1)I'll reply

  • P粉203648742

    P粉2036487422024-02-05 00:14:28

    From the @types/express-session package we can see

    /**
         * This interface allows you to declare additional properties on your session object using [declaration merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html).
         *
         * @example
         * declare module 'express-session' {
         *     interface SessionData {
         *         views: number;
         *     }
         * }
         *
         */
        interface SessionData {
            cookie: Cookie;
        }

    Therefore, you should declare the user attribute on the session object like this:

    declare module 'express-session' {
      interface SessionData {
        user: string;
      }
    }
    
    app.post('/login', express.urlencoded({ extended: false }), function (req, res) {
      req.session.user = req.body.user
    })

    Package version: "express-session": "^1.17.1"

    reply
    0
  • Cancelreply