Search code examples
javascriptnode.jsexpresscookiesexpress-session

Storing Data With Express-Session


Say you want a user to enter their email through input, and want to capture that email and persist it over multiple web-pages. Is it bad practice to store the email in the session object in express-session?

Something like:

req.session.email = '<user-email-input-from-client>'

when the client passes the email input to the server.

The use is case is later on the other web pages, I want to access the email. Using session object with req.session to see if that email exists.

function controller(req, res){
   console.log(req.session);
}
// Output: 
Session {
  cookie:
   { path: '/',
     _expires: null,
     originalMaxAge: null,
     httpOnly: true },
  email: 'test@test.com' }

and checking/using it with:

req.session.email

Is this unsafe or bad practice? Or if there is a better, more elegant way to do it, could someone give me some pointers?

Thank you in advance.


Solution

  • It is a good and secure pratice as long as you setup a "secret key".

    const express = require('express'); 
    const session = require('express-session')
    
    const app = express();
    
    app.use(session({name: "SessionID",secret: "123"}))