Sessions that never expire are a security risk. With express-session, you can force a
session to expire automatically after a period of inactivity — here, one minute.
Step 1: Initialize the project
npm init
Step 2: Install dependencies
npm install express express-session
Step 3: Configure the session
// app.js
const express = require("express");
const session = require("express-session");
const app = express();
app.use(
session({
secret: "wallet-session-secret",
resave: true,
saveUninitialized: false,
cookie: {
// Session cookie expires after 1 minute of inactivity
maxAge: 60000,
},
})
);
app.get("/wallet", (req, res) => {
if (req.session.visits) {
req.session.visits++;
res.send(`<p>Visits this session: ${req.session.visits}</p>
<p>Cookie expires at: ${req.session.cookie.expires}</p>`);
} else {
req.session.visits = 1;
res.send("New session started");
}
});
app.listen(3700, () => {
console.log("Server started on port 3700");
});
Step 4: Try it out
node app.js
Visit http://localhost:3700/wallet repeatedly within a minute and the visit counter climbs.
Stay idle for over a minute, then reload — a new session begins because the old one expired.
Why this matters
- Reduces the window an attacker has if a session cookie is stolen.
- Encourages re-authentication for sensitive actions after inactivity.
- A simple, config-only way to add a basic security control to session-based apps.