- Express.js Basics
- Express.js HOME
- Express.js Introduction
- Express.js Installation
- Express.js Basic App
- Express.js Routing
- Basics Routing
- Route Parameters
- Handling Query Strings
- Router Middleware
- Middleware
- What is Middleware?
- Application-Level Middleware
- Router-Level Middleware
- Built-In Middleware
- Error-Handling Middleware
- Third-Party Middleware
- Express.js HTTP
- Handling GET Requests
- Handling POST Requests
- Handling PUT Requests
- Handling DELETE Requests
- Templating Engines
- Using Templating Engines
- Setting Up EJS
- Setting Up Handlebars
- Setting Up Pug
- Request/Response
- Request Object
- Response Object
- Handling JSON Data
- Handling Form Data
- Static Files
- Serving Static Files
- Setting Up Static Folders
- Managing Assets
- Express.js Advanced
- Middleware Stack
- CORS in Express.js
- JWT Authentication
- Session Handling
- File Uploads
- Error Handling
- Databases
- Express.js with MongoDB
- MongoDB CRUD Operations
- Express.js with MySQL
- MySQL CRUD Operations
- Deployment
- Deploying Express.js Apps to Heroku
- Deploying Express.js Apps to AWS
- Deploying Express.js Apps to Vercel
Express.js Session Handling
Session handling in Express.js is essential for maintaining user data between HTTP requests. Sessions enable storing user-specific data such as login credentials, preferences, and other session-specific details.
Key Features of Session Handling
- State Management: Keeps user state across requests.
- Secure Storage: Sensitive data can be stored securely using server-side methods.
- Customizable: Easily integrates with different session stores like Redis or databases.
- Simple API: Middleware like
express-session
simplifies session handling.
Setting Up Session Handling in Express.js
Install the express-session
Middleware
This package is required to manage sessions.
npm install express-session
Basic Session Configuration
Add express-session
middleware to your app.
Example:
const session = require('express-session');
app.use(session({
secret: 'your_secret_key',
resave: false, // Prevents resaving unchanged sessions
saveUninitialized: true, // Saves uninitialized sessions
cookie: { secure: false } // Set to true for HTTPS
}));
Storing and Retrieving Session Data
Use the req.session
object to store and access session data.
Example:
app.get('/login', (req, res) => {
req.session.user = { username: 'JohnDoe', role: 'admin' };
res.send('User logged in');
});
app.get('/dashboard', (req, res) => {
if (!req.session.user) return res.status(401).send('Access Denied');
res.send(`Welcome ${req.session.user.username}`);
});
Destroying a Session
Use req.session.destroy()
to log out a user or clear session data.
Example:
app.get('/logout', (req, res) => {
req.session.destroy(err => {
if (err) return res.status(500).send('Unable to log out');
res.send('Logged out successfully');
});
});
Using a Session Store
By default, sessions are stored in memory, which is not suitable for production. Use session stores like Redis for scalability.
Example with connect-redis
:
npm install connect-redis redis
const RedisStore = require('connect-redis')(session);
const redis = require('redis');
const redisClient = redis.createClient();
app.use(session({
store: new RedisStore({ client: redisClient }),
secret: 'your_secret_key',
resave: false,
saveUninitialized: false
}));
Complete Example
const express = require('express');
const session = require('express-session');
const RedisStore = require('connect-redis')(session);
const redis = require('redis');
const app = express();
const redisClient = redis.createClient();
app.use(session({
store: new RedisStore({ client: redisClient }),
secret: 'your_secret_key',
resave: false,
saveUninitialized: true,
cookie: { secure: false } // Set to true if using HTTPS
}));
// Login Route
app.post('/login', (req, res) => {
req.session.user = { username: 'JohnDoe', role: 'admin' };
res.send('Logged in successfully');
});
// Dashboard Route
app.get('/dashboard', (req, res) => {
if (!req.session.user) return res.status(401).send('Access Denied');
res.send(`Hello, ${req.session.user.username}`);
});
// Logout Route
app.get('/logout', (req, res) => {
req.session.destroy(err => {
if (err) return res.status(500).send('Error logging out');
res.send('Logged out successfully');
});
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Summary
Session handling in Express.js simplifies user data management across multiple requests. Using the express-session
middleware with or without external session stores enables scalable and secure session management for modern web applications.