Open In App
Related Articles

How to expire session after 1 min of inactivity in express-session of Express.js ?

Improve Article
Save Article
Like Article

In this article, we will see how to expire the session after 1 min of inactivity in express-session of Express.js.


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:


Filename: app.js


// Call Express Api.
const express = require('express'),
    // Call express Session Api.
    session = require('express-session'),
    app = express();
// Session Setup
        // 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.
        // Session will expires after 1 min
        // of in activity
<p> Session expires after 1 min of in activity: '
+ (req.session.cookie.expires) + '</p>
    } 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 :


Output: After 1 min of inactivity it will start the new session, old session is expired.

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 20 Mar, 2023
Like Article
Save Article
Similar Reads
Complete Tutorials