Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check session in Node.js Express?

I try to check if session in Express 4 is exist:

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

It gives me error:

 Cannot read property 'user' of undefined

How I can check if exist value in session?

like image 843
Huligan Avatar asked Jun 03 '16 07:06

Huligan


4 Answers

From the source:

How to use Express Session ?

Before heading to actual code, i want to put few words about express-session module. to use this module, you must have to include express in your project. Like for all packages, we have to first include it.

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

After this, we have to initialize the session and we can do this by using following.

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

Here ‘secret‘ is used for cookie handling etc but we have to put some secret for managing Session in Express.

Now using ‘request‘ variable you can assign session to any variable. Just like we do in PHP using $_SESSION variable. for e.g

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 Session variables like sess.email , we can check whether this variable is set or not in other routers and can track the Session easily.

like image 156
Rahul Tripathi Avatar answered Nov 29 '22 11:11

Rahul Tripathi


Firstly it depends on the library you are using, maybe some libraries have utilities for that, I assume you're using express-session.

This is just Okay:

if(req.session.user){}

They are useless:

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

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

The reason: req.session is an object, just like normal objects:

var obj = { name : "adam" }

If you try to get obj.age which it doesn't exist and defined, the getter function of the object, firstly check if it exists or not, if it's not, it wouldn't produce a fatal error and instead it assigns that property to undefined value.

That's cool, so obj.age get's undefined ( JS has undefined as a value type), moreover undefined is a falsy value (when you coerce it to boolean it becomes false, so it's falsy), which means you can simply check it in conditional statements like this: if(obj.age){}

like image 35
Mehdi Raash Avatar answered Nov 29 '22 12:11

Mehdi Raash


You can't just create a session without any middleware (Im assuming this is what you've tried).

Read up on the express-session middleware docs, found here:

https://github.com/expressjs/session

Basic implementation example:

Create a session:

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

To read a 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 you can find online, e.g:

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

like image 26
James111 Avatar answered Nov 29 '22 12:11

James111


The issue you are facing is maybe you are not using the session middleware in ALL of your requests. You can check it the following way :

  1. Add this to all of 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 in any route:

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

})

This works :)

like image 35
Ayush Maheshwari Avatar answered Nov 29 '22 11:11

Ayush Maheshwari