Matt
Matt

Reputation: 649

NodeJS & ExpressJS: How to store user info in session after logged in?

I did lot of research but I am new on this, I couldn't find something concrete. When a user is logged-in I would like to store some user info in session like Name, Profile_picture, Id, so I can use it for example in the navigation bar.

How can I achieve this?

For example in PHP is too easy just adding this line of code the information stays in what ever page you visit (before session expire)

session_start();
$_SESSION['user_id']

Upvotes: 0

Views: 8459

Answers (2)

Bhaurao Birajdar
Bhaurao Birajdar

Reputation: 1507

You can use express-session or cookie-session(https://www.npmjs.com/package/cookie-session)

If you use cookie session & you made any change session variable or in server side, then no need to restart server.

It will help you to increase your development speed, because you, no need to restart server.

app.use(cookieSession({
 name: 'session',
 keys: ['key1', 'key2']
}))

app.get('/', function (req, res, next) {
  // Update views 
  req.session.views = (req.session.views || 0) + 1

  // Write response 
  res.end(req.session.views + ' views')
})

Upvotes: 1

Jesper
Jesper

Reputation: 2094

You have to create an express-session: https://www.npmjs.com/package/express-sessions

and then store the session like this:

let session = require("express-session");

app.use(session({
    secret: "secret",
    resave: false,
    saveUninitialized: true,
    cookie: {secure: true,
        httpOnly: true,
        maxAge: 1000 * 60 * 60 * 24
    }
}));

This session will be stored during your visit on the webpage. If you want to set values to the cookie, simply request the cookie in a request and set somekind of value:

router.route("/login")
    .post(function(req, res) {

        req.session.Auth = req.body.user // => user values?
    })

Upvotes: 3

Related Questions