Difference Between Session and Cookies

Last Updated : 12 May, 2026

Web applications often need to store user information such as login details, preferences, and shopping cart data. Sessions and cookies are two commonly used techniques for managing this data and maintaining user state across multiple requests.

  • Cookies store data in the user's browser and can persist even after the browser is closed.
  • Sessions store data on the server, making them more secure for sensitive information.
  • Both sessions and cookies help improve user experience by maintaining continuity between requests.
Difference-between-Session-and-Cookies
Session and Cookies

Cookie

Cookies are small data stored on the client side (browser) as key-value pairs. They are commonly used for session management, user preferences, and behaviour tracking. When a user loads a website, the browser sends the stored cookies with the request, allowing the server to track and personalize the user's experience.

Features of Cookies

  • Client-Side Storage: Data is stored in the user's browser, reducing the server's load.
  • Persistence: Can be set to expire after a specific time, allowing data to persist across sessions.
  • Small Storage Size: Limited to 4KB per cookie, making it suitable for lightweight data like preferences and authentication tokens.
  • Security: Can be configured with HttpOnly (to prevent JavaScript access), Secure (to allow only HTTPS), and SameSite (to prevent cross-site attacks).
  • Automatic Transmission: Cookies are automatically sent with every request to the same domain, enabling tracking and authentication.
  • User Tracking: Commonly used for session tracking, remembering login status, and personalization across different visits.

Use Cases of Cookies

  • Stores user preferences (e.g., theme, language settings).
  • Keep users logged in via authentication tokens (JWT).
  • Track website analytics and user behavior.
  • Manage shopping cart data in e-commerce websites.

Example: First you need to install cookie-parser in in your application

npm install cookie-parser

JavaScript
// app.js
const express = require("express");
const cookieParser = require("cookie-parser");
const app = express();

app.use(cookieParser());

app.get("/setCookie", (req, res) => {
    res.cookie("username", "GeeksForGeeks", { maxAge: 900000, httpOnly: true });
    res.send("Cookie set successfully!");
});

app.get("/getCookie", (req, res) => {
    const username = req.cookies.username;
    res.send(username ? Username: ${username} : "No cookie found");
});

app.get("/clearCookie", (req, res) => {
    res.clearCookie("username");
    res.send("Cookie deleted successfully!");
});

app.listen(3000, () => {
    console.log("Server is running on http://localhost:3000");
});

Output

Explanation: This Express.js program demonstrates cookie management using the cookie-parser middleware. It shows how to create, read, and delete cookies through different routes in a web application.

Session

Sessions in Express enable the server to maintain user-specific data across multiple requests by storing information server-side and associating it with a unique session identifier. This approach allows for persistent user interactions and state management within web applications.

Features of Sessions

  • Server-Side Storage: Stores user data securely on the server instead of the client’s browser.
  • Stateful Authentication: Maintains user login status during a session without storing credentials in cookies.
  • Large Data Storage: Unlike cookies, sessions are not limited to 4KB and can store complex data structures.
  • Automatic Expiration: Sessions expire after a certain period of inactivity or when the user logs out.
  • Session ID in Cookies: A small cookie (session ID) is used to identify the session stored on the server.
  • Security: Since the actual data is on the server, it is more secure than cookies, reducing risks like data tampering or exposure.

Use Cases of Sessions

  • Managing user authentication in web applications.
  • Storing temporary user data (e.g., items in a cart before checkout).
  • Implementing stateful applications where user data persists across multiple pages.

Example: First you need to install express-session in your application

npm install express-session

JavaScript
// app.js
const express = require('express');
const session = require('express-session');
const app = express();

app.use(session({
    secret: 'secret_key', /
    resave: false,
    saveUninitialized: true,
}));

app.get('/setSession', (req, res) => {
    req.session.username = 'GeeksForGeeks';
    res.send('Session set successfully!');
});

app.get('/getSession', (req, res) => {
    const username = req.session.username;
    if (username) {
        res.send(Username from session: ${username});
    } else {
        res.send('No active session found');
    }
});

app.get('/destroySession', (req, res) => {
    req.session.destroy((err) => {
        if (err) {
            console.error(err);
            res.status(500).send('Error destroying session');
        } else {
            res.send('Session destroyed successfully!');
        }
    });
});

app.listen(3000, () => {
    console.log('Server is running on http://localhost:3000');
});

Output

Explanation: This Express.js program demonstrates session management using the express-session middleware. It creates a session, retrieves stored session data, and destroys the session through different routes.

Cookies vs Session

FeatureCookiesSessions
Storage LocationStored in the user's browserStored on the server
SecurityLess secureMore secure
Data SizeLimited storage capacityCan store larger data
LifetimeCan persist after browser closesUsually ends after session timeout or browser close
PerformanceReduces server loadUses server memory
AccessibilityAccessible from client-side scriptsAccessible only on the server
Use CaseRemember preferences or login stateStore sensitive user information
Comment