Node Guide

Menu
Menu

Sessions

Sessions

In a Node.js/Express application, sessions are used to maintain stateful information about a user's interaction with the application across multiple requests. They enable the server to recognize and remember individual clients and provide personalized experiences.

The express-session module is a popular middleware for managing sessions in Express applications. It simplifies session handling by providing an abstraction layer and convenient APIs.

Here's a brief overview of how sessions work with express-session:

  1. When a user visits your application, a session is created on the server to store session data for that user.

  2. The session data is typically stored on the server-side, but a session identifier (usually stored in a cookie called connect.sid) is sent to the client's browser.

  3. On subsequent requests from the same client, the session identifier is sent back to the server, allowing the server to retrieve the corresponding session data.

  4. With the session data, the server can maintain user-specific information, such as authentication status, user preferences, and shopping cart contents.

The express-session module provides middleware that integrates session handling into your Express application. It abstracts the complexities of session management and provides various configuration options, such as session storage (in-memory, Redis, etc.), cookie settings, and session expiration.

npm install express-session

Require and configure the express-session middleware in your Express application. This is done with the app.use() calling the session with settings. An example would be:

The options set in the session here are:

By setting resave and saveUninitialized to false, the middleware is configured to optimize session handling by minimizing unnecessary operations when the session hasn't changed.

In a real example the secret is likely to be stored in environmental variables.

Reading and Writing Session Variables

To read session variables, you can access properties of the req.session object. For example:

In the above code, variableName is the name of the session variable you want to read. By accessing req.session.variableName, you can retrieve its value.

Writing Session Variables: To write or update session variables, you can assign values to properties of the req.session object. For example:

In this code snippet, variableName is the name of the session variable you want to create or update, and variableValue is the value you want to assign to it. By assigning a value to req.session.variableName, you can store the session variable with the specified value.

Deleting a session is performed by the req.session.destroy() method.

Note: The req.session.destroy() method will also remove the connect.sid cookie.

Sessions Example

Clone this repo to see sessions in action. This project houses a very simple login to illustrate the uses of sessions.

Ensure once cloned run:

npm install

... and launch the application with:

npm start dev

Review the src/app.ts file to see that the session has been setup importing express-session and configuring the middleware as above.

Review the routes file and notice how the /secureplace route is only accessible if a req.session.login value is set.

SNIPPET: routes/routes.ts

The POST route for login calls the postLogin controller that sets the req.session.login property if the username is 'admin' and password 'letmein' (obviously this is a basic example).

SNIPPET: controllers/controllers.ts

Run the application and login with the username is 'admin' and password 'letmein'. Notice in the Chrome Developer console a cookie of connect.sid now appears holding the session ID.

Session ID Cookie in Chrome Inspector

Logging Out by Destroying the Session

To log out of our simple application we need to remove/destroy the session. The /logout route calls the logout method in the controller.

SNIPPET: controllers/controllers.ts

The req.session.destroy() method removes the session and redirects the user to the login page.

Cookies vs Sessions

Sessions most commonly work with cookies as illustrated above.

When using the express-session middleware in Express applications, a session cookie with the name connect.sid is created and associated with each client. This cookie is used to identify and maintain the session for a particular user.

  1. Session Identification: The connect.sid cookie contains a unique session identifier. This identifier is generated by the express-session middleware when a new session is created for a user. It serves as a reference to the session data stored on the server.

  2. Cookie Name: The name connect.sid is the default name for the session cookie, but you can customize it using the name option when configuring the express-session middleware.

  3. Secure and HTTP-Only: By default, the connect.sid cookie is set with the Secure and HttpOnly flags. The Secure flag ensures that the cookie is only sent over HTTPS connections, enhancing security. The HttpOnly flag prevents client-side scripts from accessing the cookie, protecting it from certain types of attacks, such as cross-site scripting (XSS).

  4. Session Persistence: The connect.sid cookie helps maintain session persistence. It allows subsequent requests from the same client to include the session identifier, which enables the server to retrieve the corresponding session data and associate it with the request.

  5. Expiration: The connect.sid cookie typically has an expiration time defined by the express-session middleware. By default, it is a session cookie, which means it is stored in memory and expires when the user closes their browser. However, you can configure the express-session middleware to set a specific expiration time for the session cookie.

Note The connect.sid cookie is specific to the express-session middleware and may differ if you use alternative session management modules or libraries.

Next: Security with Sessions