Node.js Sessions and Cookies – A Complete Guide with Examples

Introduction

When you build a web application, you often need to remember information about a user between requests. For example, after logging in, a user should be able to visit different pages without entering their credentials every time.

HTTP is a stateless protocol, which means each request is handled independently by default. To maintain user state, applications commonly use cookies and sessions.

In Node.js, cookies can store small pieces of information in the user’s browser, while sessions allow the server to maintain user-related data between requests. Together, they are frequently used for login systems, shopping carts, user preferences, and other web application features.

In this tutorial, you will learn what cookies and sessions are, how they work in Node.js, how to implement them using Express.js, and how to protect them from common security risks.

What Are Cookies in Node.js?

A cookie is a small piece of data that a website asks the browser to store. The browser can send that cookie back to the same website with later requests, subject to its scope and security settings.

In Node.js applications, cookies are commonly used to store information such as:

  • A session identifier.
  • User preferences, such as a selected theme.
  • Language settings.
  • Other small pieces of client-side state.

For example, a website may store a session ID in a cookie. When the browser makes another request, it sends that cookie to the server, allowing the server to identify the associated session.

Cookies should not be used to store passwords or other sensitive information in plain text.

How Cookies Work

The basic cookie process works as follows:

  1. The browser sends a request to the server.
  2. The server responds with a Set-Cookie header.
  3. The browser stores the cookie according to its attributes.
  4. The browser sends the cookie with subsequent matching requests.
  5. The server reads the cookie and uses it as needed.

For example, a server might send this response header:


Set-Cookie: theme=dark; Max-Age=86400; Path=/; Secure; HttpOnly; SameSite=Lax

This example creates a cookie named theme with a value of dark. It is configured to last for one day, uses the root path, and includes security attributes. The Secure attribute means the cookie is sent only over HTTPS.

For a purely client-side theme preference, HttpOnly is optional because JavaScript may need to read the cookie. For session cookies, HttpOnly is generally recommended.

What Are Sessions in Node.js?

A session is a way for an application to maintain information about a user across multiple requests.

In a typical server-side session setup, the server stores session data, while the browser stores a session ID in a cookie. When a request arrives, the server reads the session ID and retrieves the corresponding session data.

For example, a session might contain:


{
    userId: 101,
    username: 'john',
    role: 'user'
}

This is an illustrative representation of server-side session data. In a real application, the data is managed by the session middleware and its configured session store.

Sessions are commonly used for:

  • Keeping users logged in.
  • Maintaining shopping cart information.
  • Storing temporary workflow data.
  • Tracking application state between requests.

How Sessions Work

A typical session-based login process follows these steps:

  1. The user submits login credentials.
  2. The server verifies the credentials.
  3. The server creates a session and stores relevant user information.
  4. The browser receives a cookie containing the session ID.
  5. The browser sends the cookie with later requests.
  6. The server retrieves the session and identifies the user.

The session ID acts as a reference to the server-side session. It should be treated like a secret because anyone who steals a valid session ID may be able to impersonate that session.

Difference Between Sessions and Cookies

Sessions and cookies are related, but they are not the same thing.

Cookies Sessions
Stored in the user’s browser. Commonly stored on the server or in a server-side session store.
Can contain small pieces of client-side data. Can contain application data associated with a user session.
Sent by the browser with matching requests. Usually accessed using a session ID sent in a cookie.
Can have expiration and security attributes. Can have a server-side expiration or timeout policy.
Should not contain sensitive data in plain text. Sensitive data can remain server-side, but must still be protected.

In simple terms: A cookie is stored by the browser, while a server-side session stores user-related state on the server. A session cookie often connects the browser to that server-side data.

Setting Up a Node.js Project

To work with sessions and cookies, you will use Node.js, Express.js, and the express-session package.

Create a new project:


mkdir nodejs-sessions-cookies
cd nodejs-sessions-cookies
npm init -y

Install the required packages:


npm install express express-session dotenv

The packages have the following purposes:

  • express: Creates the web server and handles routes.
  • express-session: Manages server-side sessions and session cookies.
  • dotenv: Loads configuration from environment variables.

Create a file named .env:


PORT=3000
SESSION_SECRET=replace_with_a_long_random_secret

Replace the sample session secret with a strong, randomly generated secret. Keep the .env file private and exclude it from version control.

Creating a Session in Node.js

The express-session package makes it straightforward to create and manage sessions in an Express.js application.

Create a file named app.js:


require('dotenv').config();

const express = require('express');
const session = require('express-session');

const app = express();

app.use(express.json());

app.use(
    session({
        name: 'connect.sid',
        secret: process.env.SESSION_SECRET,
        resave: false,
        saveUninitialized: false,
        cookie: {
            httpOnly: true,
            secure: process.env.NODE_ENV === 'production',
            sameSite: 'lax',
            maxAge: 1000 * 60 * 30
        }
    })
);

app.get('/', (req, res) => {
    res.send('Node.js Sessions and Cookies Example');
});

app.get('/set-session', (req, res) => {
    req.session.username = 'john';

    res.json({
        message: 'Session created successfully',
        username: req.session.username
    });
});

app.get('/get-session', (req, res) => {
    if (!req.session.username) {
        return res.status(404).json({
            message: 'Session data not found'
        });
    }

    res.json({
        username: req.session.username
    });
});

app.listen(process.env.PORT || 3000, () => {
    console.log('Server running on port 3000');
});

Understanding the Session Configuration

Here are the main options used in this example:

  • secret: Signs the session ID cookie. It should be a strong secret kept on the server.
  • resave: false: Avoids saving a session back to the store when it has not changed, where supported by the store’s behavior.
  • saveUninitialized: false: Avoids saving new sessions that have not been modified.
  • httpOnly: true: Prevents browser JavaScript from reading the session cookie.
  • secure: Sends the cookie only over HTTPS when enabled.
  • sameSite: ‘lax’: Helps limit some cross-site requests that include the cookie.
  • maxAge: Sets the cookie lifetime in milliseconds; here it is 30 minutes.

The example uses the default in-memory session store, which is suitable for local learning only. It is not suitable for production because sessions may be lost when the process restarts, and the store is not designed to scale across multiple server instances.

For production, configure a persistent session store such as Redis or a suitable database-backed store. When deploying behind a reverse proxy, configure Express’s trust proxy setting correctly if secure cookies depend on proxy-provided HTTPS information.

Testing Sessions in Node.js

Start the application:


node app.js

Open these URLs in your browser or use a tool such as Postman.

Create a session:


http://localhost:3000/set-session

The server sets username in the session and responds with a success message.

Read the session:


http://localhost:3000/get-session

If the browser sends the session cookie created earlier, the server can retrieve the stored username.

Use the same browser or HTTP client for both requests so that the session cookie is retained. If you test in a private browser window or a separate client without that cookie, the original session will not be available.

Working with Cookies in Node.js

Cookies can also be created directly in Express.js without using server-side sessions.

Express provides res.cookie() to set a cookie and res.clearCookie() to request that a cookie be removed.

For example:


app.get('/set-cookie', (req, res) => {
    res.cookie('theme', 'dark', {
        maxAge: 24 * 60 * 60 * 1000,
        httpOnly: true,
        secure: process.env.NODE_ENV === 'production',
        sameSite: 'lax',
        path: '/'
    });

    res.json({
        message: 'Cookie set successfully'
    });
});

This route creates a cookie named theme with the value dark. The browser can send it with subsequent requests that match the cookie’s scope and security settings.

If you want client-side JavaScript to read a theme preference, do not set httpOnly: true for that particular cookie. Keep HttpOnly enabled for session cookies and other cookies that JavaScript does not need to access.

Reading Cookies

To read cookies in Express, you can use the cookie-parser package.

Install it:


npm install cookie-parser

Then add this code:


const cookieParser = require('cookie-parser');

app.use(cookieParser());

app.get('/get-cookie', (req, res) => {
    const theme = req.cookies.theme;

    res.json({
        theme: theme || 'default'
    });
});

The middleware parses the incoming Cookie header and makes the values available through req.cookies.

Remember that client-provided cookies can be modified. Never trust a cookie value as proof of identity or permission unless it is validated through an appropriate secure mechanism.

Deleting a Cookie

To clear a cookie, use res.clearCookie() with the appropriate cookie scope:


app.get('/clear-cookie', (req, res) => {
    res.clearCookie('theme', {
        path: '/',
        sameSite: 'lax',
        secure: process.env.NODE_ENV === 'production'
    });

    res.json({
        message: 'Cookie cleared'
    });
});

The cookie name and relevant attributes should match the cookie you originally set. Clearing a browser cookie does not automatically delete any server-side session data associated with it.

Destroying a Session During Logout

When a user logs out of a session-based application, the server should destroy the session. It should also clear the corresponding session cookie.

For example, add this route to the session application:


app.post('/logout', (req, res, next) => {
    req.session.destroy((err) => {
        if (err) {
            return next(err);
        }

        res.clearCookie('connect.sid', {
            path: '/',
            httpOnly: true,
            sameSite: 'lax',
            secure: process.env.NODE_ENV === 'production'
        });

        res.json({
            message: 'Logged out successfully'
        });
    });
});

Mistakes When Using Sessions and Cookies

Here are some mistakes developers should avoid:

  • Using the default session store in production: It is intended for development and testing.
  • Forgetting to configure HTTPS cookies: Cookies without appropriate security settings may be exposed to greater risk.
  • Trusting cookie values blindly: Client-side values can be changed, so validate them server-side.
  • Not destroying sessions on logout: A session that remains valid may continue to grant access.
  • Using weak session secrets: Weak secrets can compromise session-cookie integrity.
  • Ignoring CSRF protection: Cookie-based authentication needs appropriate protection for state-changing requests.
  • Assuming cookie deletion destroys the session: The server-side session should also be invalidated.
  • Failing to regenerate the session ID after login: This can expose the application to session fiThis route destroys the server-side session and asks the browser to clear the session cookie.
  • The cookie name must match the name option in your session configuration. In this example, that name is connect.sid.
  • For an application deployed behind a reverse proxy, make sure the secure cookie configuration and Express proxy settings match the production environment.
  • Sessions and Cookies Security Best Practices
  • Sessions and cookies are useful, but they must be configured carefully.
  • 1. Use HTTPS
  • Use HTTPS to protect cookies while they travel between the browser and the server. Enable the Secure attribute for cookies in production.
  • 2. Enable HttpOnly for Session Cookies
  • The HttpOnly attribute prevents client-side JavaScript from reading the cookie. This reduces the risk of session-cookie theft through certain cross-site scripting attacks, although it does not eliminate XSS risks.
  • 3. Configure SameSite Appropriately
  • The SameSite attribute can limit when browsers send cookies with cross-site requests. Select a policy that fits your application, and implement additional CSRF protection where required.
  • 4. Use a Strong Session Secret
  • Use a strong, randomly generated session secret. Store it in an environment variable or secrets manager rather than hard-coding it into your source code.
  • 5. Use a Production Session Store
  • Do not rely on the default in-memory session store in production. Use a supported persistent store and configure expiration, cleanup, and availability appropriately.
  • 6. Regenerate Sessions After Login
  • Regenerate the session ID after successful authentication to help prevent session fixation attacks. A typical implementation calls req.session.regenerate() after credentials have been verified and before saving the authenticated user’s information.
  • 7. Set Session Expiration
  • Use appropriate session timeouts and destroy sessions when users log out. For sensitive applications, consider both idle timeouts and absolute session lifetime limits.
  • 8. Avoid Storing Sensitive Information in Cookies
  • Cookies can be exposed to the client and may be sent with HTTP requests. Store only the information that is necessary in cookies, and avoid placing passwords, private keys, or sensitive personal data in them.
  • 9. Protect Against CSRF
  • Cookie-based authentication can be vulnerable to cross-site request forgery because browsers may attach cookies automatically. Use suitable CSRF defenses for state-changing requests, especially when cross-site cookies are allowed.
  • Common xation risks.

Conclusion

Sessions and cookies are important concepts in Node.js web development. Cookies allow browsers to store small pieces of data and send them with matching requests, while server-side sessions let applications maintain user-related state between requests.

Using Express.js and express-session, you can create sessions, retrieve session data, and destroy sessions during logout. Express also provides methods for setting and clearing cookies, while cookie-parser can help read incoming cookie values.

For production applications, use HTTPS, secure cookie attributes, a suitable session store, strong secrets, session ID regeneration after login, and appropriate CSRF protection. These practices help build safer and more reliable Node.js applications.

Related Node.js Tutorials