What are express user sessions and how can I utilize them with JavaScript for controlling routes and SQL database queries?

Jake Rudlong
5 min readMar 28, 2023

--

A ‘req.session’ is an Express.js object that represents/temporarily stores important information about a current user’s session on your app/website. To get the most out of this tutorial, let’s assume that you are using express.js, node.js, have a bit of node.js-based SQL experience with an npm package like mysql2, and are using an object-relational-mapper like sequelize (specific articles on using SQL queries with mysql2 and ORM principles coming soon, but until then check out the docs for both in the links provided). Most apps involve some form of user identity (i.e. the ability of a user to signup → resulting in them being added to your database with login credentials and other information stored).

While different authentication libraries can help verify if a username/password combo matches a user in the database, and libraries like bcrypt can keep your password hashed and safe, how can you reference given attributes of a user after they sign in to make queries to your SQL database that are centered around your user? This is where we can utilize an important npm package simply called express-session.

After installing the package, a good place to start is in your server.js file, where you can include it with a ‘require’ statement or ‘import’ statement:

const express = require('express'); // of course include express too
const session = require('express-session');
const app = express();

Next, we can set up some information for our session:

const sess = {
secret: 'Super secret secret',
cookie: {},
resave: false,
saveUninitialized: true,
store: new SequelizeStore({
db: sequelize,
}),
};
app.use(session(sess));

For additional security, we can set up a session secret (in this example it is ‘super secret secret’); we have included the use of a cookie, which will store information about the session (usually directly in the browser memory) and set a unique session id for every session. Cookies can have more information such as session expiration/timeout length. Because we do not care about the specific cookie name, path, or want a specific expiration for the cookie, we do not assign any specific values to the cookie. Setting resave to false tells the session middleware not to resave the session when it’s not necessary (i.e. if nothing about the session has changed). We can also connect session info to an ORM like sequelize for reasons we will get into. the last bit of code in the block above just tells app (express) to use the session middleware we defined, with those specific config details.

Now that we have defined our session details and linked it with express properly, we can start utilizing sessions in some of the routes for our app. One of the most important uses of sessions is upon user login. A user that exists in your database signs in and, assuming the login was successful, we can then save a session with certain information about that user (from the database). Take a look at the following code snippet for a POST route pulled from a recent project for logging into an app:

router.post('/login', async (req, res) => {
try {
const userData = await User.findOne({
where: { email: req.body.email },
});
// code for verifying whether the user details are valid...
// if everything checks out, we can then save our session by referencing
// details about that user from the database
req.session.save(() => {
req.session.logged_in = true;
req.session.user = {
id: userData.id,
name: userData.name,
location: userData.location,
gender: userData.gender,
};
res.json({ user: userData, message: 'You are now logged in!' });
});
// any other code that might be included in the post route...

This code takes the login details, and if the login info is valid, certain details of the user will be saved to a session — their id, name, location, and gender, in this example. One could include other fields that included in the user model that you might need to reference. Now, this is all fine, but the point of this essay is to explore how we can use this session information in our routes/queries to make requests that only affect the user that is signed in. You may think of a PUT request (tied to an SQL update query — it would be dangerous to not properly restrict the query to just the specific user that happens to be signed in at the time of the query. This could result in changing every single user in your database inadvertently. Thankfully, express session data is fairly easy to use once the session has been defined in your server file and properly linked in your files. Let’s take a look at an example of a PUT route to update a user’s location, where we specify the query to only target the user tied to our session (i.e. the user that is currently logged in).

router.put('/', async (req, res) => {
try {
console.log(req.session.user);
const dbUserData = await User.update(
{
location: req.body.location,
},
{
where: { // here we specify *only* the current session user
id: req.session.user.id,
},
}
);

res.status(200).json(dbUserData);

} catch (err) {
console.log(err);
res.status(500).json(err);
}
});

Here we have a location column being updated in a table (model) called User, and we are specifying the update query to only target columns where user.id (the id column of the User table) is equal to the id of the current logged-in user (req.session.user.id). This is only one simple example of how we can reference attributes of a logged-in user by referring to the current session object.

In addition to referencing our sessions to aid in sequelize queries, we can control whether some pages of our app/website are accessible only when a user is logged. In the example directly below, we describe a route to a ‘messages’ page from our homepage. The conditional (if statement) simply checks whether there is a current session (i.e. is someone logged in) when trying to navigate from the homepage (e.g. the user has clicked on a navbar link). If there is no session, the user will be redirected to the login page instead of being taken to whatever page they were trying to access (in this example, a messages page):

router.get('/messages', async (req, res) => {
try {
if (!req.session.user) {
return res.redirect('/login');
}

// whatever code would be executed if they are logged in

});

To sum up, express sessions are conceptually simple yet important features of a well-made express app. The examples listed in this tutorial are only a small glimpse of what can be done with sessions, but I hope you find it helpful!

Happy coding!

--

--