Skip to content

3. Session Handling

A session is a way to store user data on the server between HTTP requests.

Since HTTP is stateless (it doesn’t remember anything between requests), sessions help us keep track of who the user is and what they’re doing across multiple requests (like staying logged in, remembering items in a cart, etc.).

Here’s how it works:

  1. Client (browser) makes a request.
  2. Server assigns a unique session ID and stores data on the server (in memory, Redis, database, etc.).
  3. The session ID is sent to the client as a cookie.
  4. On future requests, the client sends that cookie back.
  5. Server uses the session ID to retrieve the user’s data.

Example:

User: GET /login
Server: Sets session.user = "nadith", sends Set-Cookie: sessionId=abc123
User: GET /dashboard
Server: Gets sessionId=abc123 → session.user = "nadith"

Sessions vs Cookies:

  • Session = data stored on server (client only gets a session ID).
  • Cookie = data stored on the client, sent with every request.

1. ExpressJS and Session

In Express.js you can save data in the session using middleware like express-session.

1. Install express-session:

Terminal window
npm install express-session

2. Setup and use it in your Express app:

const express = require('express');
const session = require('express-session');
const app = express();
app.use(session({
secret: 'your_secret_key', // used to sign the session ID cookie
resave: false, // don't save session if unmodified
saveUninitialized: true // save new sessions
// saveUninitialized: false // This means no session is saved unless something is stored.
}));
app.get('/set', (req, res) => {
req.session.username = 'Nadith';
res.send('Session value set');
});
app.get('/get', (req, res) => {
res.send(`Hello ${req.session.username || 'Guest'}`);
});
app.listen(3000, () => console.log('Server running on http://localhost:3000'));

Output:

  • Visit /set → sets the session variable.
  • Visit /get → returns “Hello Nadith” if session is still active.

2. Redis to Store Session

Sure! Here’s how to use Redis as a session store in Express with express-session.

1. ✅ Install dependencies

Terminal window
npm install express express-session connect-redis redis

2. ✅ Set up Express with Redis session store

const express = require('express');
const session = require('express-session');
const RedisStore = require('connect-redis').default;
const { createClient } = require('redis');
const app = express();
const redisClient = createClient();
redisClient.connect().catch(console.error); // Connect to Redis
// Create Redis store
const redisStore = new RedisStore({
client: redisClient,
prefix: 'sess:', // optional key prefix
});
app.use(session({
store: redisStore,
secret: 'your_secret_key',
resave: false,
saveUninitialized: false,
cookie: {
secure: false, // set true if using HTTPS
httpOnly: true,
maxAge: 1000 * 60 * 10, // 10 minutes
}
}));
// Routes
app.get('/set', (req, res) => {
req.session.username = 'Nadith';
res.send('Username saved in Redis session');
});
app.get('/get', (req, res) => {
const name = req.session.username || 'Guest';
res.send(`Hello ${name}`);
});
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});

3. 🧪 Test it

  1. Go to http://localhost:3000/set
  2. Then go to http://localhost:3000/get — you’ll see: Hello Nadith