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
:
When a user visits your application, a session is created on the server to store session data for that user.
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.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.
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.
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:
secret
: This option is required and specifies the secret used to sign the session ID cookie. It is used to prevent tampering of the session cookie by adding a unique and secret value. You should choose a strong secret string for enhanced security.resave
: This option determines whether the session should be saved to the session store on every request, even if the session data hasn't changed. Setting it tofalse
indicates that the session should only be saved if it has been modified during the request. This helps optimize performance by avoiding unnecessary writes to the session store.saveUninitialized
: This option determines whether a session should be saved to the session store if it is new and hasn't been modified. Setting it tofalse
means that only sessions with modifications will be saved. This helps reduce storage usage by omitting empty, uninitialized sessions.
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:
... and launch the application with:
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.
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).
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.
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.
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.
Session Identification: The
connect.sid
cookie contains a unique session identifier. This identifier is generated by theexpress-session
middleware when a new session is created for a user. It serves as a reference to the session data stored on the server.Cookie Name: The name
connect.sid
is the default name for the session cookie, but you can customize it using thename
option when configuring theexpress-session
middleware.Secure and HTTP-Only: By default, the
connect.sid
cookie is set with theSecure
andHttpOnly
flags. TheSecure
flag ensures that the cookie is only sent over HTTPS connections, enhancing security. TheHttpOnly
flag prevents client-side scripts from accessing the cookie, protecting it from certain types of attacks, such as cross-site scripting (XSS).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.Expiration: The
connect.sid
cookie typically has an expiration time defined by theexpress-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 theexpress-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