How to expire session after 1 min of inactivity in express-session of Express.js ?
In this article, we will see how to expire the session after 1 min of inactivity in express-session of Express.js.
Prerequisites
- Installation of Node.js on Windows
- To set up Node Project in Editor see here.
Requires Modules:
npm install express npm install express-session
Call API:
var session = require('express-session')
To expire the session after 1 min of inactivity in the express-session of Express.js we use expires: 60000 in the middleware function.
Project Structure:
The below example illustrates the above approach:
Example:
Filename: app.js
Javascript
// Call Express Api. const express = require( 'express' ), // Call express Session Api. session = require( 'express-session' ), app = express(); // Session Setup app.use( session({ // It holds the secret key for session secret: "I am girl" , // Forces the session to be saved // back to the session store resave: true , // Forces a session that is "uninitialized" // to be saved to the store saveUninitialized: false , cookie: { // Session expires after 1 min of inactivity. expires: 60000 } }) ); // Get function in which send session as routes. app.get( '/session' , function (req, res, next) { if (req.session.views) { // Increment the number of views. req.session.views++ // Session will expires after 1 min // of in activity res.write( ' <p> Session expires after 1 min of in activity: ' + (req.session.cookie.expires) + '</p> ' ) res.end() } else { req.session.views = 1 res.end( ' New session is started' ) } }) // The server object listens on port 3000. app.listen(3000, function () { console.log( "Express Started on Port 3000" ); }); |
Steps to run the program:
Run the index.js file using the below command:
node app.js
Now to set your session, just open the browser and type this URL :
http://localhost:3000/session
Output: After 1 min of inactivity it will start the new session, old session is expired.
Please Login to comment...