How to check session in Node.js Express?

I am trying to check if a session exists in Express 4:

if(req.session.user == undefined) {} 

This gives me an error:

  Cannot read property 'user' of undefined 

How can I check if a value exists in a session?

+5
source share
4 answers

From source:

How to use express session?

Before moving on to the actual code, I want to say a few words about the express session module. To use this module, you need to enable express in your project. As with all packages, we must first enable it.

 server.js var express = require('express'); var session = require('express-session'); var app = express(); 

After that, we must initialize the session, and we can do this using the following.

 app.use(session({secret: 'ssshhhhh'})); 

Here the "secret" is used to process cookies, etc., but we need a secret to manage the session in Express.

Now, using the query variable, you can assign a session to any variable. Just like in PHP using the $ _SESSION variable. eg,

 var sess; app.get('/',function(req,res){ sess=req.session; /* * Here we have assign the 'session' to 'sess'. * Now we can create any number of session variable we want. * in PHP we do as $_SESSION['var name']. * Here we do like this. */ sess.email; // equivalent to $_SESSION['email'] in PHP. sess.username; // equivalent to $_SESSION['username'] in PHP. }); 

After creating the session variables, such as sess.email, we can check whether this variable is set or not in other routers and can track the Session easily.

+7
source

You can't just create a session without any middleware (I assume this is what you tried).

Read the express session middleware documents that can be found here:

https://github.com/expressjs/session

An example of a basic implementation:

Create Session:

 app.use(session({ genid: function(req) { return genuuid() // use UUIDs for session IDs }, secret: 'keyboard cat' })) 

To read the session:

 // Use the session middleware app.use(session({ secret: 'keyboard cat', cookie: { maxAge: 60000 }})) // Access the session as req.session app.get('/', function(req, res, next) { var sess = req.session if (sess.views) { sess.views++ res.setHeader('Content-Type', 'text/html') res.write('<p>views: ' + sess.views + '</p>') res.write('<p>expires in: ' + (sess.cookie.maxAge / 1000) + 's</p>') res.end() } else { sess.views = 1 res.end('welcome to the session demo. refresh!') } }) 

There are a number of tutorials that you can find on the Internet, for example:

https://www.thepolyglotdeveloper.com/2015/01/session-management-expressjs-web-application/

+4
source

Firstly, it depends on the library you are using, maybe there are utilities for some libraries, I suppose you are using express-session .

It is just OK:

 if(req.session.user){} 

They are useless:

 if(typeof req.session.user !== "undefined"){} if(typeof req.session.user !== "undefined" || req.session.user === true){} 

Reason : req.session is an object, just like regular objects:

 var obj = { name : "adam" } 

If you try to get obj.age that it does not exist and is not defined, the getter function of the object, first of all, check if it exists or not, if it is not, it will not lead to a fatal error , and instead it assigns it the property value is undefined .

This is cool, so obj.age get undefined (JS has undefined as a value type), moreover undefined is a fake value (when you force it to boolean, it becomes false, so it is false), which means you can just check it in conditional statements as follows: if(obj.age){}

+4
source

The problem you are facing is that you may not be using session middleware in ALL of your requests. You can check it as follows :

  • Add this to all your routes:

 app.use(session({ secret: 'keyboard cat',resave:false,saveUninitialized:false, cookie: { maxAge: 60000 }})); 
  1. Authentication Route:

 router.post('/', function(req, res, next) { //login logic here //if login successfull req.session.user = username //your unique identifier req.send("Hurray! logged in"); //else req.send("Credentials error"); }); 
  1. Check out any route:

 router.get('/dashboard', function(req, res, next) { if (req.session.user) //do stuff here else //redirect to login page }) 

It works:)

0
source

All Articles