A website is based on the HTTP protocol. HTTP is a stateless protocol which means at the end of every request and response cycle, the client and the server forget about each other. Show This is where the session comes in. A session will contain some unique data about that client to allow the server to keep track of the user’s state. In session-based authentication, the user’s state is stored in the server’s memory or a database. How sessions worksWhen the client makes a login request to the server, the server will create a session and store it on the server-side. When the server responds to the client, it sends a cookie. This cookie will contain the session’s unique id stored on the server, which will now be stored on the client. This cookie will be sent on every request to the server. We use this session ID and look up the session saved in the database or the session store to maintain a one-to-one match between a session and a cookie. This will make HTTP protocol connections stateful. The difference between session and cookieAs you might have noticed, we’ve introduced a new concept called a cookie. We need to answer the question of what is the difference between a session and a cookie. A cookie is a key-value pair that is stored in the browser. The browser attaches cookies to every HTTP request that is sent to the server. In a cookie, you can’t store a lot of data. A cookie cannot store any sort of user credentials or secret information. If we did that, a hacker could easily get hold of that information and steal personal data for malicious activities. On the other hand, the session data is stored on the server-side, i.e., a database or a session store. Hence, it can accommodate larger amounts of data. To access data from the server-side, a session is authenticated with a secret key or a session id that we get from the cookie on every request. To learn more about their differences, check this Session vs Cookie tutorial. Prerequisites
Setting up the required environments and librariesThis is a Node.js project. It uses NPM to manage its dependencies. You need to create a new project directory and initialize the node app using: This will generate a The following libraries will help us setup a Node.js session.
Install the above libraries using the command:
Express-session options and how to use themTo set up the session, you need to set a couple of Express-session options, as shown below.
Check the documentation for all possible options and learn more about these options. Setting up the session middlewareTo initialize the session, we will set the session middleware inside the routes of the individual HTTP requests. When a client sends a request, the server will set a session ID and set the cookie equal to that session ID. The cookie is then stored in the set cookie HTTP header in the browser. Every time the browser (client) refreshes, the stored cookie will be a part of that request. We’ll create a simple login form to demonstrate that. Create a
Let’s
setup the server. Create an Import all the Node.js libraries that we explained earlier
Initialize the express app
Add the Express-session options
Parse the HTML formThis will help us parser an HTTP POST method request from an HTML document. We also need to serve the CSS styling to format the outlook of the HTML form. Add the following express methods to perform these operations.
Set the Cookie-parserDefine Cookie-parser usage so that the server can access the necessary option to save, read and access a cookie.
Set the authentication credentialsIn this
example, we are using a simple login application. To authenticate the user, I’ve specified the username and password as In a production environment, these credentials are usually saved in a database. For the sake of simplicity in this tutorial, we are storing them in these variables.
Add the endpointsWe have to make three routes here:
This will render and serve the HTML form to the client to fill in the login credentials. If the user is logged in, we’ll display a logout link.
To create a session, the user will submit the credentials. The server will verify these credentials received in the request’s body with the username and the password for the existing user. If the credentials are valid:
Once the client browser saves this cookie, it will send that cookie along with each subsequent request to the server. The server will validate the cookie against the session ID. If the validation is successful, the user is granted access to the requested resources on the server. If the credentials are invalid, the server will not grant this user access to the resources. No session will be initialized, and no cookie will be saved.
This will define the logout endpoint. When the user decides to log out, the server will destroy (
Listen to the port of the server
Your session application is now set. Run the application using: This should start the server on the set port 4000. Open the server on the browser on route To be authenticated by the server, provide the credentials specified in the server: username as Once you log in successfully, a session will be generated, and a cookie will be saved in the browser. In this case, since we don’t have a database to save the session, we will These are the same values you would have saved in a production environment on the server-side into a database such as MongoDB, PostgreSQL, etc. Let’s see the cookie value saved in the browser. Open the browser inspector tool > application > Cookies http://localhost:4000/. Every time you refresh this page, the request will be sent along with the value of this cookie within this localhost domain. If it matches with the session stored value, the server will authenticate this user. It’s not a security concern if a third party can read the cookies. The client won’t be able to modify the contents of the cookie, and even if they try to, it’s going to break the signature of that cookie. This way, the server will be able to detect the modification. A cookie doesn’t carry any meaningful data
inside of them. It just contains the session ID token. The cookie is encrypted. It still has to maintain a one-to-one relationship with the user session. The cookie will be valid until set When the user logs out, the session will be destroyed. There is no session to compare with the saved cookie. The user will have to log in again to create a session ID for the new login session. ConclusionThat’s all for this tutorial. This was a basic example, and I hope it helped you understand the concept of session management in Node.js using Express.js and Express-session. Happy coding!! Peer Review Contributions by: Mohan Raj |