Express.js Sessions
While cookies are stored on the client, **sessions** store data on the server. Sessions are essential for maintaining user state across multiple requests � keeping users logged in, storing shopping cart contents, and more. Express works with session middleware to provide this functionality.
What are Sessions?
Sessions are server-side storage for user data. Each session has a unique ID, which is typically stored in a cookie on the client. When the client makes subsequent requests, the session ID is sent, and the server retrieves the corresponding session data.
Think of sessions as a secure locker at a gym. You get a key (session cookie), and the gym keeps your belongings (session data) safely. Only you with the key can access them.
Installing Express Session
npm install express-sessionconst session = require('express-session');
app.use(session({ secret: 'my-secret-key', <!-- Used to sign the session ID cookie --> resave: false, <!-- Don't save session if unmodified --> saveUninitialized: false, <!-- Don't create session until something stored --> cookie: { secure: false, maxAge: 60000 } <!-- 1 minute -->}));Working with Session Data
Session data is attached to the request object as `req.session`. You can read and write properties directly.
<!-- Store data in session -->app.get('/set-session', (req, res) => { req.session.username = 'john'; req.session.visits = (req.session.visits || 0) + 1; res.send('Session data set');});
<!-- Read session data -->app.get('/get-session', (req, res) => { const username = req.session.username; const visits = req.session.visits || 0; if (!username) { return res.send('No session data found'); } res.send(`Welcome back, ${username}! You've visited ${visits} times.`);});Destroying Sessions
To log out a user, you need to destroy their session:
app.get('/logout', (req, res) => { req.session.destroy((err) => { if (err) { return res.status(500).send('Could not log out'); } res.send('Logged out successfully'); });});Session Options Explained
| Option | Description |
|---|---|
secret | Used to sign the session ID cookie (required). |
resave | Forces session to be saved back to the store (false recommended). |
saveUninitialized | Saves new sessions that are unmodified (false recommended). |
cookie.secure | Only send cookie over HTTPS (set true in production). |
cookie.maxAge | Session expiration in milliseconds. |
Practical Example: Login System with Sessions
const express = require('express');const session = require('express-session');const app = express();
app.use(express.urlencoded({ extended: true }));
app.use(session({ secret: 'your-secret-key', resave: false, saveUninitialized: false, cookie: { maxAge: 30 * 60 * 1000 } <!-- 30 minutes -->}));
<!-- Login page (simplified) -->app.get('/login', (req, res) => { res.send(` <form method=""POST"" action=""/login""> <input type=""text"" name=""username"" placeholder=""Username""><br> <input type=""password"" name=""password"" placeholder=""Password""><br> <button type=""submit"">Login</button> </form> `);});
<!-- Handle login -->app.post('/login', (req, res) => { const { username, password } = req.body; <!-- Validate credentials (replace with real validation) --> if (username === 'admin' && password === 'secret') { <!-- Store user info in session --> req.session.user = { username, role: 'admin' }; res.redirect('/dashboard'); } else { res.send('Invalid credentials'); }});
<!-- Protected route -->app.get('/dashboard', (req, res) => { if (!req.session.user) { return res.redirect('/login'); } res.send(`Welcome ${req.session.user.username}! This is your dashboard.`);});
<!-- Logout -->app.get('/logout', (req, res) => { req.session.destroy(() => { res.redirect('/login'); });});Session Stores in Production
By default, sessions are stored in memory. This doesn't scale well. In production, use a database store like Redis or MongoDB:
npm install connect-redis redis
const RedisStore = require('connect-redis')(session);const redis = require('redis');const client = redis.createClient();
app.use(session({ store: new RedisStore({ client }), secret: 'your-secret', resave: false}));Two Minute Drill
- Sessions store user data on the server, with a session ID stored in a cookie.
- Use `express-session` middleware to enable sessions.
- Session data is available at `req.session` � read and write directly.
- Destroy sessions with `req.session.destroy()` for logout.
- In production, use a persistent store like Redis instead of default memory storage.
Need more clarification?
Drop us an email at career@quipoinfotech.com
