Express Sessions
Express.js, a Node.js framework, enhances web applications with express-session for session management. This middleware overcomes the stateless nature of HTTP by enabling persistent user sessions, stored in server memory or a database. It transforms HTTP interactions into stateful experiences, allowing the server to recognize and track users across requests with unique session IDs, ensuring continuous user-state monitoring and enhanced security.
How do Sessions Work?
The server will construct a session and save it on the server side after receiving a login request from the client. When the server answers to the client, it transmits a cookie. The unique id for the session that was previously stored on the server will be found in this cookie and will be kept on the client. Every time a request is made to the server, this cookie will be transmitted. To preserve a one-to-one match between a session and a cookie, we use this session ID to look for the session maintained in the database or the session store. As a result, HTTP protocol connections will become stateful.
The Flow of Cookie-based Session Management
- New login request is sent by the browser to the server.
- The server will then determine if any cookies have been sent by the browser.
- There isn't going to be a cookie value inside the server database for this request because it is a new one.
- As a result, the server will send a cookie to your browser and store its ID there.
- The browser will then create the cookie for the domain of that server.
- Your browser should deliver the cookie in the HTTP header with each request for that server's website.
- The ID given by the browser will then be checked by Server. Then, the server will use the session indicated by the cookie if that is the case.
For express sessions, we create a session in middleware.
Place the express session middleware before every route to ensure that the incoming request has a session. Middleware will :
- Examine the cookie to see if the session ID is still valid.
- If so, look in the session store for the appropriate session ID and retrieve the information.
- If the answer is no, make a fresh session and include it in the request object. Moreover, generate a session ID cookie based on the middleware's cookie settings.
Paramters Description
Cookie.secure: For automatic alignment with the connection's security level, the cookie.the secure option can optionally be set to the unique value "auto". If the site is accessible via both HTTP and HTTPS, use caution when utilizing this setting because after the cookie is placed on HTTPS, it is no longer visible over HTTP.
Name: The term to set in the response for the session ID cookie. The value by default is connect.sid.
Resave: Regardless of whether the express session was modified during the request, it is forced to be saved back to the session store. This may be required depending on your store, depending on the store you use. It can also lead to race conditions where the server receives two parallel requests from the client side. Even if the other request did not make any changes, any modifications made to the session in the first request might be overridden when it concludes. True is the default value, although using the default has been discouraged because it may change in the future.
Rolling: Constrain all responses to set the express session identifier cookie. The expiration countdown is reset, and the expiration is set to the initial maxAge. False is the default setting.
saveUninitialized: makes it necessary to save an uninitialized session to the store. When a session is created but not yet updated, it is uninitialized. False is a good option if you want to implement login sessions, utilize less server storage, or adhere to rules that demand consent before setting a cookie. False will also help in race-condition situations where a client sends out many requests concurrently without using a session. True is the default value, although using the default has been discouraged because it may change in the future.
Secret: That is a necessary choice. The express session ID cookie is signed using this secret. This could be an array of many secrets or a string for a single secret. Only the first member of an array of secrets will be used to sign the session ID cookie; however, all elements will be taken into account for determining whether the signature in requests is valid.
store: A new MemoryStore object by default serves as the session store instance.
unset: Control the outcome of req.session being unset (through delete, setting to null, etc.). Keep is the default value.
cookie: { maxAge: oneDay } : this determines when cookies expire. Following the specified period, the browser will remove the cookie. In the future, no requests will have the cookie associated with them. The following math was used to calculate the maxAge in this situation, which was set to one day.
cookie.path: Specifies the Path Set-Cookie value. This is set to '/' by default, which is the domain's base path.
cookie.httpOnly: The HttpOnly Set-Cookie attribute's conditional value is specified. The HttpOnly property is set when truthy; otherwise, it is not. The HttpOnly attribute is enabled by default. Be careful when setting this to true, as compliant clients will not allow client-side JavaScript to see the cookie in document.cookie.
cookie.domain: Specifies the Domain Set-Cookie property value. By default, no domain is specified, and most clients will interpret the cookie to only pertain to the current domain.
cookie. expires: The Date object is specified as the value for the Expires Set-Cookie property. By default, no expiration date is set, and most clients will regard this as a "non-persistent cookie" and delete it when a circumstance such as exiting a web browser application occurs.
cookie.sameSite: Specifies whether the SameSite Set-Cookie property should be boolean or string. This is set to untrue by default.
true will set the SameSite attribute to Strict for strict same-site enforcement. false will not set the SameSite attribute.
- lax will set the SameSite attribute to Lax for lax same-site enforcement.
- none will set the SameSite attribute to None for an explicit cross-site cookie.
- strict will set the SameSite attribute to Strict for strict same-site enforcement.
The Difference Between Session and Cookie
Cookie:
Let's try to distinguish between cookies and sessions using the following example. Cookies can be compared to an identity card. Hence, when we visit a workplace for the first time, we lack an ID card. If we don't have an ID, we must prove our identification each time we enter the workplace.
The business will provide an ID card if we ask for one when we arrive for the first time. So, we are not required to reveal our identity each time we visit. That ID card will serve as our identification. Our firm ID card will be more than sufficient if we present it. The security officer will then let us. In a similar vein, the HTTP request in a browser's initial request to a server won't contain a cookie value. To prevent this, the server will create a new cookie for that browser session and transmit it along with the reply. Hence, the cookie for that domain will be stored by the browser.
A key-value pair is saved in the browser as a cookie. Every HTTP request that is delivered to the server by the browser comes with cookies attached. You can't save a lot of information in a cookie. Cookies cannot be used to store any kind of user credentials or confidential data. If we did that, a hacker might simply obtain that information and steal people's personal information for illegal purposes. This is because the cookies are saved on the client side mostly on the random access memory (for example: in Firefox, all cookies are stored in a single file, located in the Firefox profile folder). Hence cookies can be accessed by hackers with some effort but sessions or in general express sessions are encrypted and stored on the server side which makes it safer than cookies.
When Should I Use Cookies?
As the HTTP protocol is stateless, cookies let us monitor the status of the application using small files kept on the user's machine. The browser determines where the cookies are stored. These are often saved by Internet Explorer in the Temporal Internet Files folder. Allowing consumers to choose their preferences allows for the personalization of the user experience. Based on the choices set in the cookies, the requested page that comes next is customized. Monitoring a user's page visits.
When Should I Use Sessions?
To more securely keep sensitive data on the server, out of the reach of malevolent users, such as the user id. Values are transferred across pages using express session. It can also be used to store global variables more effectively and securely than by passing them in the URL when creating applications like shopping carts that need to temporarily store data with a capacity greater than 4KB. On platforms that do not allow cookies, it can also be used as a substitute for cookies.
The Major Difference Between Cookies and Session
Cookie | Session |
---|---|
Cookies are client-side files stored locally on a computer that contain user data. | User data stored in the server side is called sessions. |
Cookies expire when the user-defined lifespan expires. | The session ends when the user closes the browser or logs out of the software. |
It has a limited capacity for information storage. | It has a practically infinite capacity for data storage. |
We don't need to run a function to start cookies because they are stored locally on the machine. | The session start() function must be used to start the session. |
Cookies are not secured. | When compared to cookies, sessions are more secure. |
Cookies save information to a text file. | Session saves data in encrypted form. |
Installation
Prerequisites
- Install the Node.js runtime on your PC.
- Basic understanding of Node.js use.
- Knowledge of the rudiments of building an HTTP server with the Expres.js module.
This module for Node.js is accessible from the npm registry. The npm install command is used for installation :
Session Store Implementation
Every express session store needs to implement certain methods and be an EventEmitter. The mandatory suggested and optional techniques are listed in the paragraphs that follow.
-
This module will always call the required methods on the store.
-
If applicable, this module will call for recommended methods for the store.
-
Optional methods are those that this module does not use at all but that aid in the user presentation of consistent stores.
-
store.all(callback) : optional
All express sessions in the store can be obtained as an array using this optional function. The callback should be used to refer to as callback(error, sessions).
-
store.destroy(sid, callback) : required
With a session ID, this necessary function is used to remove/destroy a session from the storage (sid). Once the session is terminated, the callback should be invoked as a callback(error).
-
store.clear(callback) : optional
All express sessions in the store can be deleted using this optional technique. Once the store has been cleaned, the callback should be invoked as callback(error).
-
store.length(callback) : optional
The number of all sessions in the shop can be obtained using this callback. The callback should be invoked as callback(error, len).
-
store.get(sid, callback) : required
When a session ID is provided, this necessary method is used to retrieve a session from the store (sid). The callback should be invoked as a callback(error, session).
-
store.set(sid, session, callback) : required
With an express session ID (sid) and session (session) object, this necessary function is used to upsert a session into the store. Once the session has been set up in the store, the callback should be invoked as callback(error).
Compatible Session Stores
The following modules implement an express-session-compatible express-session store.
- connect-memcached: A session store compatible with memcached.
- connect-dynamodb: A session store compatible with DynamoDB.
- @google-cloud/connect-datastore: A session store compatible with Google Cloud Datastore.
- cassandra-store: An session store compatible with Apache Cassandra.
- firestore-store: A session store compatible with Firestore.
- session-file-store: A session store compatible with the file system.
- @quixo3/prisma-session-store: A session store compatible with the Prisma Framework.
- memorystore: A session store for memory in production.
- connect-mongodb-session: A Lightweightsession store developed and maintained by MongoDB that is compatible with MongoDB.
- express-sessions: A session store compatible with both MongoDB and Redis.
- express-mysql-session: A session store that is developed using native MySQL via the node-mysql module.
- connect-sqlite3: an SQLite3 session store based on the connect-redis store used by TJ.
- connect-typeorm: A session store compatible with TypeORM.
- connect-session-sequelize: A session store using Sequelize.js, which is an io.js ORM / Node.js for MSSQL, MySQL, PostgreSQL, and SQLite.
- connect-pg-simple: A session store compatible with PostgreSQL.
- connect-redis: A session store compatible with Redis.
- sessionstore: A session store compatible with different databases.
- connect-mongo: A session store compatible with MongoDB.
- connect-session-firebase: A Firebase Realtime Database-based session store.
- connect-session-knex: A session store developed using Knex.js, which is a SQL query builder for Oracle, SQLite3, MariaDB, MySQL, and PostgreSQL.
Session Management in Node.js Using ExpressJS and Express Session
An easy example of storing page views for a user using express session.
Debugging
Internally, this module logs details about express session activities using the debug module.
When starting your program (using npm start in this case), specify the DEBUG environment variable to express the session to view all internal logs :
Conclusion
- HTTP is a stateless protocol, the client and server forget about one another after each request and response cycle.
- The stateless HTTP protocol is used by a website to transport data from a client to a server.
- Sessions enable the HTTP protocol to go from being stateless to stateful.
- A session can be thought of as the period between logging in and logging out.
- As the HTTP protocol is stateless, cookies let us monitor the status of the application using small files kept on the user's machine.
- Cookies stored by the browser can hold a maximum of 4 KB.
- This npm install command is used for express-session installation : $ npm install express-session
- Every express session store needs to implement certain methods and be an EventEmitter.