Difference between sessions and cookies in Express
Last Updated :
24 Jul, 2024
Express.js is a popular framework for Node.js, that is used to create web applications. It provides tools to manage user sessions and cookies. The session and cookies are used to maintain the state and manage user authentication. In this article, we will learn about what sessions and cookies in Express and their differences.
Cookies in Express:
Cookies are small pieces of data that are stored on the client side (browser) in the form of a key-value pair. Cookies are used for session management, user preference,a and tracking of user behavior. when user loads the website a cookie is sent with the request that helps us to track the user's actions.
To use cookies in Express, you have to install the cookie-parser package, It is a middleware that is used to parse cookies from the incoming request.
npm install cookie-parser
Example:
JavaScript
//app.js
const express = require("express");
const cookieParser = require("cookie-parser");
const app = express();
// Middleware to parse cookies from the request
app.use(cookieParser());
//Route to set the cookie
app.get("/setCookie", (req, res) => {
// Setting a cookie
res.cookie("username", "GeeksForGeeks");
res.send("Cookies set successfully!");
});
//Route to retrieve the cookie
app.get("/getCookie", (req, res) => {
//Retrieving cookies from the request
const username = req.cookies.username;
res.send(`Username: ${username}`);
});
//Route to delete the cookie
app.get("/clearCookie", (req, res) => {
// deleting a cookie
res.clearCookie("username");
res.send("Cookie deleted successfully!");
});
app.listen(3000, () => {
console.log("Server is running on port 3000");
});
To Run the Application, Type the following command in terminal:
node index.js
Output
Session in Express:
A session is a feature in Express that let you maintaining state and user-specific data across multiple requests. sessions stores information at a server side with a unique session identifier. In a session you assign a unique session id to the client. After that client makes all request to the server with that unique id.
To use session in a Express, you have to install express-session package, It is a middleware that is used to provides a simple API for creating, reading, and updating session data.
npm install express-session
Example:
JavaScript
//app.js
const express = require('express');
const session = require('express-session');
const app = express();
// Middleware to enable sessions
app.use(session({
secret: 'secret_key',
resave: false,
saveUninitialized: true,
}));
//Route to set the session
app.get('/setSession', (req, res) => {
// Setting session data
req.session.username = 'GeeksForGeeks';
res.send('Session set successfully!');
});
//Route to retrieve the session
app.get('/getSession', (req, res) => {
// Retrieving session data
const username = req.session.username;
res.send(`Username from session: ${username}`);
});
//Route to destroy the session
app.get('/destroySession', (req, res) => {
// Destroying the session
req.session.destroy((err) => {
if (err) {
console.error(err);
} else {
res.send('Session destroyed successfully!');
}
});
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
To Run the Application, Type the following command in terminal:
node index.js
Output
Difference between Session and Cookies in Express
Session | Cookies |
---|
A session is stored at server side | A cookie is stored at client side |
It can store a data ranging between 5mb - 10mb | It can only store a data of 4kb |
It is destroyed when user logout. | It is destroyed when user closes the page or it will remain until the defined time. |
express-session middleware is required to create a session. | It doesn't require any middleware to create a cookie. Express provide built in support. |
Session id is used as a identifier. | Key-value pair data is used as a identifier. |
The performance of session is slower due to server interaction. | The performance of cookie is faster, as data is stored locally. |
It is more secure as data are stored at server side. | It is less secure as data are stored at client side. |
It is used for storing user-specific data. | It is used to store user preference data. |
Similar Reads
Difference Between Session and Cookies When building a website, we need to remember user information whether it's login details, preferences, or shopping cart items. Two common ways to store this data are sessions and cookies.Cookies are small pieces of data stored in the user's browser. They help remember things like login status or pre
6 min read
Difference between req.cookies and req.signedCookies in Express.js req.cookies: Request. Cookies are supposed to be cookies that come from the client (browser) and Response. Cookies are cookies that will send back to the client (browser). Cookies are small files/data that are sent to the client with a server request and stored on the client side. This helps us to k
3 min read
What are the difference between session and cookies in PHP ? Both sessions and cookies are important for maintaining state and storing data in PHP. However, they differ significantly in terms of how and where they store data, their lifespan, security features, and use cases. In this article, we will explore the key differences between sessions and cookies in
4 min read
Difference Between Local Storage, Session Storage And Cookies The HTTP protocol is one of the most important protocols for smooth communication between the server and the client. The main disadvantage of the HTTP protocol is that it is a stateless protocol, which means it does not track any kind of response or request by the server or the client. So, to resolv
6 min read
Difference between app.get() and app.post() in Express.js. In ExpressJS, app.get() and app.post() are two different methods used to handle HTTP requests but for different purposes. app.get() in ExpressJS:app.get() is used to handle incoming GET requests. GET requests are commonly used for fetching data from the server. For example, when you open a website i
2 min read