User Authentication with Express.js

jakesweb profile image Jacob Colborn ・2 min read

Part of making an Express.js based application is being able to authenticate users. The question after getting them authenticated is what to do with that?

My current strategy is to use a client-side cookie that is encrypted with a secret hash. To create a session, I use both the cookie-parser and express-session modules. I link them to my application with app.use in app.js.

const cookieParser = require('cookie-parser');
const session = require('express-session');

    secret: application_secret,
    resave: false,
    saveUninitialized: false

Using that setup we can create sessions with req.session. With the login route on the user router, we can set the session.

router.post('/login', (req,res) => {
    // login the user and return the user object
    // if the login is successful
    req.session.email = user.email;
    req.session.role = user.role

This sets the email and the role to the user session. I defined three roles so far: student, instructor, and admin. There are two ways that I use these roles right now. In the routes, I can run an if statement that renders a different page or passes a different property to the templates.

if (req.session.role === 'student') {
} else if (req.session.role === 'admin') {
} else {

That's not the most relevant example; you would typically check if the user is authenticated and then render a page if they are or redirect if they aren't. The other option is to take a middleware. In my middlewares directory I have admin-auth.js which defines a middleware.

module.exports = function(req,res,next) {
    if (req.session.role === 'admin') {
    } else {

Then on the route that I want to check if there is an admin authentication with the middleware. The middleware will process before the route is allowed to continue processing.

const authAdmin = require('../middlewares/auth-admin');

router.get('/admin', authAdmin, (req,res) => {

What this will do is pass the request to the middleware first. The middleware checks the role in the user session, and if the role is an admin role it allows the route to continue with next(). The else path changes this to the unauthorized webpage if the user doesn't have a role or the role is not an admin role.

Posted on by:

jakesweb profile

Jacob Colborn


Trying to learn javascript and taking everyone on the ride with me.


markdown guide