req.Session in Node.js

Asked

Viewed 2,443 times

2

I would like to know how the basic req.Session structure of Node.js. Is it native to Express or express-Session? Please help me understand more about sessions.

2 answers

2

it is installed separately using the "npm install express-Session --save command"

then put this in your main file:

app.use(session({
    secret: '2C44-4D44-WppQ38S',
    resave: true,
    saveUninitialized: true
}));

And to create a new session variable, follow the example:

req.session.usuario = usuario;

And a basic middleware to authenticate would be:

module.exports = function(req, res, next) {
  if(!req.session.usuario) {
      return res.redirect('/');
  }
    return next();
};
  • I’ve been doing some research and I can understand, thanks for the help!

0

It is not native to express, it is necessary to install it by

NPM: npm i express-session

or

Yarn: yarn add express-session

As far as I know it is a safer way to store information that needs to be protected, such as a token generated by jwt.

express Session is a middleware that needs to be called in your main file this way:

const serverSession = require('express-session')


.use(serverSession({ secret: sua-chave-secreta, resave: false, saveUninitialized:false }))

Your secret key needs to be generated at md5 if I’m not mistaken and stored securely.

Read the documentation to understand correctly how it works documentation

I hope I’ve helped.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.