Express js Sessions

As we know HTTP is a stateless protocol, when a user requests one page, followed by another, HTTP does not provide a way for you to tell that both requests came from the same user.

The idea of session control is to be able to track a user during a single session on a website.


Install express-session

To use session, first we need to install express-session, it stores user sessions across different browsers.


npm install --save express-session

Include express-session

To use express session, we need to include this in our code.

var session = require('express-session')

Set sessions

The req.session object is used to set session variable.

req.session.name = 'Jorz';

Delete a session

The delete keyword is used to delete session.

delete req.session.name;

Express session example

var express = require('express');
var session = require('express-session');

var app = express();

var sessionOptions = {
  secret: "secret",
  resave : true,
  saveUninitialized : false
};

app.use(session(sessionOptions));

app.get("/", function(req, res){
  if ( !req.session.views){
    req.session.views = 1;
  }else{
    req.session.views += 1;
  }
 res.json({
    "status" : "ok",
    "frequency" : req.session.views
  });
});

app.listen(3300, function (){
  console.log("Server started at: http://localhost:3300");
});