ExpressJS Session

Express Session is a middleware of ExpressJS used to session information, like Session ID.

Session stores data on server side. Only Session ID is available on client side cookie . Session data is saved till user session is active. Once user left, session data is no more.

Install Express Session

npm i express-session

Express Session v1.5.0 and above don't require cookie parser middleware.


Session API

After installing Express Session, first include the module in main app. Then the app.use middleware is used to call module.

app.set is used to trust first proxy.

    
const express=require('express');
const app=express();
const session=require('express-session');

    // trust first proxy
app.set('trust proxy', 1); 

app.use(session({
    secret:"session",
    resave:false,
    saveUninitialized:true,
    cookie:{secure:false}
}))

app.listen(3000,()=>{
    console.log("server running")
})        

Session ID

Each session has a unique id associated with id, popularly known as Session ID. Its a unique id and cannot be modified. To get session ID, use req.sessionID.

    /*app.js*/
const express=require('express');
const app=express();
const session=require('express-session');

app.set('trust proxy', 1); 

app.use(session({
    secret:"session",
    resave:false,
    saveUninitialized:true,
    cookie:{secure:false}
}));

app.get('/',(req,res)=>{
    res.send('Session ID :  '+ req.sessionID);
  })

app.listen(3000,()=>{
    console.log("server running")
})     

Run App

Session ID : Ec0hZL5dXL6zuJn23nrcbG6GR4Mq7C7V

node src/app.js


Page Views

In this example, we will create a counter for page views by a user session.

    /*app.js*/
const express=require('express');
const app=express();
const session=require('express-session');
const parseurl=require('parseurl');

app.set('trust proxy', 1); 

app.use(session({
    secret:"session",
    resave:false,
    saveUninitialized:true,
    cookie:{secure:false}
}));

app.use(function (req, res, next) {
    if (!req.session.views) {
      req.session.views = {}
    }
  
    // get the url pathname
    var pathname = parseurl(req).pathname
  
    // count the views
    req.session.views[pathname] = (req.session.views[pathname] || 0) + 1
  
    next()
  })

app.get('/',(req,res)=>{
    res.send('Session Views :  '+ req.session.views['/'] + ' times');
  })

app.listen(3000,()=>{
    console.log("server running")
})     

Run App

Session Views: 1 times

node src/app.js

Now refresh your browser to see increment, but session id will remain same

To start a new session, copy url and paste in another browser or incognito mode. By default, new session starts with 1 times.


Secure

Secure Cookie is possible on website using https. To secure session, use cookie:{secure:true} option. Now session will be secure.

  
const express=require('express');
const app=express();
const session=require('express-session');

app.set('trust proxy', 1); 

app.use(session({
    secret:"session",
    resave:false,
    saveUninitialized:true,
    cookie:{secure:true}
}));

secure cookies is recommended for all websites using https.


Maxage

maxAge option is used to set age of cookie in MilliSeconds.

   
const express=require('express');
const app=express();
const session=require('express-session');

app.set('trust proxy', 1); 

app.use(session({
    secret:"session",
    cookie:{maxAge:60000}
}));
    // session will expires after 60sec