req.session.user - Property 'User'; does not exist on type 'Session'; error while trying to pass session data using express session
P粉593536104
P粉593536104 2024-02-04 09:05:25
0
1
446

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粉593536104
P粉593536104

reply all(1)
P粉203648742

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"

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template