Cookies and sessions are essential components of web development, enabling applications to maintain state and persist user data across different requests. Understanding how to effectively use cookies and sessions in Express.js will allow you to create more interactive and secure web applications.
In this chapter, we’ll dive deep into the concepts of cookies and sessions, exploring their basics, how they work in Express.js, and advanced use cases. By the end, you’ll have a thorough understanding of how to manage user data and state across multiple requests.
Cookies are small pieces of data stored on the client-side (in the user’s browser) that are sent with every HTTP request to the server. They are often used to remember user preferences, session data, or tracking information.
Cookies have the following characteristics:
In Express.js, setting and reading cookies is straightforward, thanks to the cookie-parser
middleware.
First, install the cookie-parser
middleware:
npm install cookie-parser
To use cookies in your Express.js application, you need to set up cookie-parser
as middleware.
cookie-parser
app.js
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
const port = 3000;
// Use cookie-parser middleware
app.use(cookieParser());
// Route to set a cookie
app.get('/set-cookie', (req, res) => {
res.cookie('username', 'JohnDoe', { maxAge: 900000, httpOnly: true });
res.send('Cookie has been set');
});
// Route to read a cookie
app.get('/get-cookie', (req, res) => {
const username = req.cookies.username;
res.send(`Cookie Value: ${username}`);
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
req.cookies
object.username
with the value JohnDoe
. The cookie has a maximum age of 15 minutes and is marked as httpOnly
, meaning it cannot be accessed via client-side JavaScript./set-cookie
sets the username
cookie./get-cookie
reads and displays the value of the username
cookie
Cookie Value: JohnDoe
Cookies come with various options that control their behavior, including security settings like httpOnly
and secure
.
document.cookie
).app.js
// Route to set a secure cookie
app.get('/set-secure-cookie', (req, res) => {
res.cookie('sessionToken', 'abc123', {
maxAge: 3600000, // 1 hour
httpOnly: true,
secure: true,
sameSite: 'Strict',
});
res.send('Secure cookie has been set');
});
Cookies can be deleted by setting their expiration date to a time in the past.
app.js
// Route to delete a cookie
app.get('/delete-cookie', (req, res) => {
res.clearCookie('username');
res.send('Cookie has been deleted');
});
username
cookie by setting its expiration date to a time in the past.Navigating to /delete-cookie
deletes the username
cookie, making it unavailable in future requests.
Sessions are a server-side storage mechanism used to store user data across multiple HTTP requests. Unlike cookies, which store data on the client-side, sessions keep the data on the server and use a cookie (typically a session ID) to associate the session with the client.
To manage sessions in Express.js, you can use the express-session
middleware.
express-session
First, install the express-session
middleware:
npm install express-session
express-session
app.js
const session = require('express-session');
// Use express-session middleware
app.use(session({
secret: 'your-secret-key',
resave: false,
saveUninitialized: true,
cookie: { maxAge: 60000 } // 1 minute
}));
// Route to set a session value
app.get('/set-session', (req, res) => {
req.session.user = 'JohnDoe';
res.send('Session has been set');
});
// Route to get the session value
app.get('/get-session', (req, res) => {
const user = req.session.user;
res.send(`Session Value: ${user}`);
});
/set-session
sets the session value for user
./get-session
retrieves and displays the session value
Session Value: JohnDoe
express-session
provides several options to customize session behavior:
maxAge
, httpOnly
, secure
, and sameSite
.app.js
app.use(session({
secret: 'your-secret-key',
resave: false,
saveUninitialized: false,
cookie: {
maxAge: 60000, // 1 minute
httpOnly: true,
secure: false,
sameSite: 'Strict'
},
rolling: true
}));
By default, sessions are stored in memory, which is not suitable for production. Instead, you can use session stores like Redis, MongoDB, or a database to persist sessions.
First, install the required packages:
npm install connect-redis redis
app.js
const RedisStore = require('connect-redis')(session);
const redis = require('redis');
// Create a Redis client
const redisClient = redis.createClient();
// Configure express-session to use Redis
app.use(session({
store: new RedisStore({ client: redisClient }),
secret: 'your-secret-key',
resave: false,
saveUninitialized: false,
cookie: { maxAge: 60000 }
}));
express-session
that uses Redis as the backend.Securing sessions is critical to protect user data and prevent session hijacking. Here are some best practices:
httpOnly
Cookies: Prevent client-side access to the session cookie.app.js
// Route to regenerate session ID after login
app.post('/login', (req, res) => {
// Assuming authentication is successful
req.session.regenerate((err) => {
if (err) {
return res.status(500).send('Error regenerating session');
}
req.session.user = 'JohnDoe';
res.send('Logged in successfully');
});
});
In some cases, you may want to combine cookies and sessions, such as using a cookie to store a session token that identifies a session stored on the server.
app.js
// Route to set a session and cookie
app.get('/login', (req, res) => {
const sessionToken = 'abc123';
res.cookie('sessionToken', sessionToken, { maxAge: 3600000, httpOnly: true });
req.session.token = sessionToken;
res.send('Logged in and session started');
});
// Route to access session via cookie
app.get('/dashboard', (req, res) => {
const sessionToken = req.cookies.sessionToken;
if (sessionToken === req.session.token) {
res.send('Welcome to your dashboard');
} else {
res.status(401).send('Unauthorized access');
}
});
/login
sets both a session and a session token cookie./dashboard
checks if the session token in the cookie matches the session, granting access if they match.In this chapter, we've covered the fundamentals of cookies and sessions in Express.js, including how to set, read, and manage them securely. Cookies and sessions are crucial for maintaining state in web applications, allowing you to track user activities and store important data across multiple requests.Happy coding !❤️