Learn

Data in a session is serialized as JSON when stored, so we’re able to store and access data in nested objects. Let’s say we had saved the number of items in a user’s cart in the session data:

req.session.user.cartCount = 2;

We can then access it by referring to req.session.user.cartCount when we need to display the correct number of items. We can also update its value.

One common use case of session data is to protect specific routes. In the example below, we check that the authorized property exists within the session, and if it’s set to true before we move on to the next route handler.

function authorizedUser(req, res, next) { // Check for the authorized property within the session if (req.session.authorized) { // next middleware function is invoked res.next(); else { res.status(403).json({ msg: "You're not authorized to view this page" }); } };

In the protected route, we can also pass the user session object:

app.get("/protected", authorizedUser (req, res, next) { res.render("protected", { "user": req.session.user }); };

NOTE: res.render() takes in a view page as the first argument and an object whose properties define local variables for the view as the second argument.

In the workspace, we have some code that corresponds to the same website from the last exercise. Let’s implement the examples from above!

Instructions

1.

In the previous exercise, we set an authenticated property and a user object for every session created through the middleware. Let’s explore how we can make use of that session data to make this site fully functional with a user session!

The ensureAuthentication function is provided to protect routes from unauthenticated users. Complete the code in the function to check if the authenticated property in session exists and is set 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.

2.

Add ensureAuthentication to the "/shop" route as a middleware. This triggers the ensureAuthentication function to run and check the req.session.authenticated value in order to access the shop page.

3.

The "/shop" route is currently sending a hardcoded username to the view page.

Replace "Guest" with the user object a from the session. This will pass that object into the view page. This website is now functional and making use of session data!

You may run the completed code in your local Node environment. We’re attaching a zipped file of the project here.

Take this course for free

By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.
Already have an account?