express-session is middleware that manages user sessions — storing data on the server and
tracking each visitor via a cookie. It's the backbone of login persistence in many Express
apps.
Step 1: Create the project
mkdir session-demo
cd session-demo
npm init -y
Step 2: Install dependencies
npm i express
npm i express-session
Step 3: Write the app
// app.js
const express = require("express");
const session = require("express-session");
const app = express();
const port = 5100;
app.use(session({
secret: "cart-secret-key",
resave: false,
saveUninitialized: true
}));
app.get("/add-to-cart", (req, res) => {
req.session.cartItem = "Wireless Keyboard";
res.send(`Item added! Now visit <a href="/cart">/cart</a> to view it.`);
});
app.get("/cart", (req, res) => {
const item = req.session.cartItem || "Your cart is empty";
res.send(`Cart contents: ${item}`);
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
Step 4: Run it
node app.js
Visiting /add-to-cart then /cart in the same browser shows the item persisted in the
session, even though no database is involved.
Common uses
- Keeping a user logged in across requests.
- Building shopping-cart-like features without a full auth system.
- Storing temporary, per-visitor state on the server.