With a session middleware configured, we can now make use of the session and combine it with an authentication process.

On the right, we have a login form that takes a username and password. If a user logs in with the correct credentials, we want to initiate a session.

We can do this by first looking up the user in our database and then verifying that the password is correct. Once credentials are confirmed, we’ll add data to our session.

Once the user is logged in we’ll add a property, authenticated within our session object and assign it to true. We’ll also set user in the session data and assign it the username and password we received:

// Look up user in database, if found, confirm password: if (password == "[email protected]") { // Attach an `authenticated` property to our session: req.session.authenticated = true; // Attach a user object to our session: req.session.user= { username, password, } }

Note: we are demonstrating using a hardcoded password. However, in production, you always want to encrypt your password.

Once the user is logged in, their session is created and stored in memory. The properties authenticated and user will be accessible and changeable as session data.



Scroll down to the app.post request for logging users in.

Once the user is authenticated within the POST request for "/login", create an authenticated property attached to the session object and assign it to true.

Type node app.js into the Terminal to start the node app.

Press the Check Work button to check your work for each checkpoint.


Create a new property in the session called user and assign it to an object with the username and password as both properties and their values.


Output the session in the terminal after creating the user object.


In the terminal run the command:

node app.js

Press the circular arrow button in the mini-browser to load the webpage. An image showing a cursor pressing the refresh button to refresh the iframe which contains a mini-browser.

In the mini-browser, log in with the username sam, and the password [email protected].

Once logged in, the terminal should log out information regarding the session you created.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?