How to Expire Session After 1 Min of Inactivity in express-session of Express.js ?
To automatically expire sessions after 1 minute of inactivity in an Express.js application using express-session, configure the session settings with the cookie.maxAge
and implement session touch logic to track activity.
Approach
To expire the session after 1 min of inactivity in the express-session of Express.js we use expires: 60000 in the middleware function.
Syntax:
const session = require('express-session')
Expiring sessions after inactivity helps secure your applications.
Steps to Implement Auto-Expire Session in Express
Step 1: Create an “app.js” file and initialize your project with npm.
npm init
Step 2: Now install two npm packages: “express” and “express-session“.
npm install express express-session
Project Structure:
Updates dependencies in package.json file
"dependencies": {
"express": "^4.19.2",
"express-session": "^1.18.0",
}
Example: The below example illustrates the above approach.
// Filename - app.js
// Call Express Api.
const express = require('express'),
// Call express Session Api.
const session = require('express-session'),
const 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.