Express.js Session
What is Session?
A session is a way to store user data on the server across multiple HTTP requests. Session help maintain user data across multiple requests such as authentication status, user preferences, or temporary data.
Why Use Session?
- Stateless nature of HTTP: HTTP is stateless, meaning each request is independent. Sessions help maintain user state.
- Secure storage: Unlike cookies (which store data on the client), sessions store data on the server.
- Better for sensitive data: Since data is not exposed in the browser, it's harder to tamper with.
How Sessions Work in Express.js
- The server creates a session and assigns it a unique session ID (SID).
- The session ID is stored in a cookie on the client’s browser.
- On each request, the client sends the session ID cookie back to the server.
- The server retrieves the session data using the session ID and responds accordingly.
Install Dependencies
npm install express
npm install express-session
Setting Up Session in Express.js Server
index.jsconst express = require('express'); const session = require("express-session"); const app = express(); app.use( session({ secret: "your-secret-key", // Used to sign session ID cookie resave: false, // Avoids resaving unchanged session data saveUninitialized: true, // Saves new sessions even if empty cookie: { maxAge: 60000 }, // Session expires after 1 min }) ); const PORT = 5000; app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); });
- The Express.js server is configured with express-session.
- It manages user sessions by storing session data on the server.
- Session cookies expire after 1 minute.
Storing and Retrieving Session Data
You can store user data in req.session and retrieve it later.
Store Data in Session
app.get("/set-session", (req, res) => { req.session.name = "Ram"; // Storing data res.send("Session data saved!"); });
Retrieve Stored Session Data
To access stored session data
app.get("/get-session", (req, res) => { if (req.session.name) { res.send(`Hello, ${req.session.name}`); } else { res.send("No session found."); } });
Destroying a Session
To log out a user or clear session data.
app.get("/destroy-session", (req, res) => { req.session.destroy((err) => { if (err) { return res.send("Error destroying session"); } res.send("Session destroyed!"); }); });
Run the Server
Run the server using the command is given below.
node index.js
D:\my-app>node index.js Server is running on http://localhost:5000
Output
The output shows how session data is stored.

The output shows how session data is fetch.

The output shows how session data is destroy.

When Should We Use Sessions?
- User authentication (login systems)
- Shopping carts (e-commerce sites)
- Temporary user settings (e.g., filters, preferences)