26/11/20 — Introducing Sessions

Acebookgroup2
2 min readNov 27, 2020

As HTTP is stateless, we needed to associate each request to another request and store user data between these requests.

This would help us keep track of users through our web application, make a more secure platform, and offer a more personalised experience.

How did we do it?

First, we downloaded the Express Sessions module using NPM and required it in our app.js file by assigning it to a session variable.

Using the app.use function, we called the session variable and assigned it a secret resave and a saveUninitialized attribute. The secret is a key used to sign in and encrypt cookies which helps us to maintain the session state. We set the resave and saveUnitialized attributes to false to make sure the session only saves if it was modified.

In the posts controller, we implemented an ‘if’ statement in the index function so that if our session was empty then it would redirect the user back to the Homepage. This prevents users from seeing posts unless they have logged in.

‘If’ statement in the Index function of our /controller/posts.js file

In the render function we set the test attribute to be equal to req.session.test. We then assigned it a value in the home controller inside the login user function. This means that when the user logs in, req.session.test variable is no longer empty and they will have access to the web app. We also added it to the create user function so that users are automatically redirected to the post page once signed up.

Our session variable in /controller/home.js

--

--