How to Expire session after a specific time of inactivity in Express.js

In this article, we will learn how to expire the session after a specific time of inactivity in Express.js. For this, we would be requiring an express-session module.

Expiring a session after a specific time of inactivity in Express.js

We are required to install two modules and we can do that by typing this on the terminal:

npm i express 
npm i express-session

After that, we will include the modules needed by require() method and use app.listen() to make sure our server is running.

var express = require('express'), 
session = require('express-session'), 
app = express(); 
app.listen(3000, function () { 
    console.log("Express server Started on Port 3000"); 
});

Then we use app.use() to set up our session,

app.use(session({
 secret: 'keyboard',
 resave: true,   
 saveUninitialized: false,
 cookie: { maxAge: 30000 }   
}))

Here we set different options in session. In the cookie.maxAge is used to determine the specific time after which the session expires due to inactivity, and the secret is used to store the secret key for the session.

Later on, we use app.use() to call the middleware function where req.session is used to store and access the session data and use that to show different output after 30 seconds when the previous session had expired.

app.use(function(request, response, next) {
   var reqsession = request.session
   if (reqsession.views) {
     reqsession.views++
     response.write('<p>New window will appear after refresh</p>')
     response.write('<p>expires in: ' + (reqsession.cookie.maxAge / 1000) + 's</p>')
     response.end()
   } else {
     reqsession.views = 1
     response.end('welcome to the new session demo. refresh!')
   }
 })

 

Here’s the complete code:

var express = require('express'),
session = require('express-session'),
app = express();
app.use(session({
    secret: 'keyboard',
    resave: true,
    saveUninitialized: false,
    cookie: { maxAge: 30000 }
 }))
  app.use(function(request, response, next) {
    var reqsession = request.session
    if (reqsession.views) {
      reqsession.views++
      response.write('<p>New window will appear after refresh</p>')
      response.write('<p>expires in: ' + (reqsession.cookie.maxAge / 1000) + 's</p>')
      response.end()
    } else {
      reqsession.views = 1
      response.end('welcome to the new session demo. refresh!')
    }
  })
app.listen(3000, function () {
    console.log("Express server Started on Port 3000");
});

Output:

Expire session after a specific time of inactivity in Express.js

After clicking on refresh after 30 seconds,

req.session

Leave a Reply

Your email address will not be published. Required fields are marked *