Expire Express.js Session After 1 Minute of Inactivity

Last Updated : 26 Sep, 2026

To automatically expire a session after 1 minute of inactivity in an Express.js application using express-session, configure the session cookie with the maxAge option.

Approach

To expire the session after 1 minute of inactivity, set cookie.maxAge to 60000 milliseconds in the express-session middleware. The cookie expiration is refreshed when the session is accessed, so the session can expire after the specified period without activity.

Syntax:

const session = require("express-session");

Expiring inactive sessions can help reduce the risk of unauthorized access to session-based applications.

Implement Auto-Expire Session

Follow the steps below to configure a session that expires after 1 minute of inactivity.

Step 1: Create an app.js file and initialize the Node.js project.

npm init -y

Step 2: Install express and express-session.

npm install express express-session

Project Structure:

The package.json file will contain the installed dependencies. The exact versions may vary depending on when the packages are installed.

Example: The following example configures an Express.js session to expire after 1 minute of inactivity.

Node
// app.js

const express = require("express");
const session = require("express-session");

const app = express();

// Session setup
app.use(
    session({
        // Secret key used to sign the session ID cookie
        secret: "my-secret-key",

        // Avoid unnecessary session-store saves
        resave: false,

        // Do not save uninitialized sessions
        saveUninitialized: false,

        cookie: {
            // Session expires after 1 minute of inactivity
            maxAge: 60 * 1000
        }
    })
);

// Session route
app.get("/session", (req, res) => {
    if (req.session.views) {
        // Increment the number of views
        req.session.views++;

        res.send(
            `Session is active. Views: ${req.session.views}<br>
             Session expires at: ${req.session.cookie.expires}`
        );
    } else {
        req.session.views = 1;
        res.send("New session is started");
    }
});

// Start the server
app.listen(3000, () => {
    console.log("Express server started on port 3000");
});

Steps to Run the Program

Step 1: Run the app.js file using the following command:

node app.js

Step 2: Open a browser and visit:

http://localhost:3000/session 

The first request creates a new session:

New session is started

Subsequent requests within the 1-minute inactivity period access the existing session and increment the view count.

If no request touches the session for 1 minute, the session cookie expires and a subsequent request starts a new session.

Output:

Comment