Session and Cookie Management with Express.js
Session and Cookie Management with Express.js
In web applications, managing sessions and cookies is extremely important to enhance user experience and temporarily store user information. Express.js, written in JavaScript, offers a useful infrastructure for handling such data. In this article, we will learn how to manage sessions and cookies in Express.js.
Session Management
Session temporarily stores data during users' interactions with a web application. For session management in Express.js, we typically use the express-session middleware. First, we need to add this package to our project. Here is a basic configuration:
npm install express-session
In the example below, we create a simple Express.js application to demonstrate session usage:
const express = require('express');
const session = require('express-session');
const app = express();
app.use(session({
secret: 'secretKey', // Secret key for session
resave: false,
saveUninitialized: true,
}));
app.get('/', (req, res) => {
req.session.visits = (req.session.visits || 0) + 1; // Update visit count
res.send(`You have visited this page ${req.session.visits} times.`);
});
app.listen(3000, () => {
console.log('Application running on port 3000');
});
Cookie Management
Cookies are pieces of data stored in the user's browser. When the user visits the application again, cookie information can be retrieved from the browser and used. To use cookies in Express.js, installing the cookie-parser middleware is necessary:
npm install cookie-parser
In the example below, we show a simple cookie creation and reading process:
const cookieParser = require('cookie-parser');
app.use(cookieParser());
app.get('/setcookie', (req, res) => {
res.cookie('user', 'Ali', { maxAge: 900000, httpOnly: true }); // Create cookie
res.send('Cookie has been created.');
});
app.get('/getcookie', (req, res) => {
res.send(`Cookie Value: ${req.cookies.user}`); // Read cookie
});
Conclusion
Session and cookie management with Express.js is critical for enhancing user experience and monitoring user interactions in web applications. In this article, we learned with a simple structure how to store and use user information. By enriching your applications with these methods, you can provide a more interactive experience for your users.

Yorum Gönder