DEV Community

Cover image for Express Middleware as the Nightclub Bouncer: Ensuring VIP Access to Your App
Joshua Medina
Joshua Medina

Posted on

Express Middleware as the Nightclub Bouncer: Ensuring VIP Access to Your App

Middleware functions are functions that have access to the request object (req), the response object (res), and the next function in the application’s request-response cycle.
-Expressjs.com

Welcome to the blog post where we're going to unravel the intriguing world of middleware and how it transforms into the "bouncer" of your web application! Imagine your web app is like a bustling nightclub, and you, as the app owner, want to ensure that only VIP guests (authenticated users) get access to the exclusive party. That's where middleware steps in, just like a vigilant bouncer stationed at the club's entrance. In this post, we'll explore how middleware can serve as a security guard, managing who gets in (authenticated users) and who gets turned away (unauthorized visitors).

What is Middleware?

In the context of web development using frameworks like ExpressJS, middleware is a special type of function that sits between the incoming request from the client and the response sent back by the server. It has the power to intercept and process the request before it reaches the main route handler. This clever functionality allows developers to add extra features, security measures, or custom logic to their applications without cluttering the main code. This will also help developers maintain DRY code.

Authentication Middleware

Authentication middleware is used to check whether a user is authenticated (logged in) before granting access to certain routes or resources. When a user makes a request to a protected route, the authentication middleware is executed before the route handler. The middleware examines the request to determine whether the user is authenticated. If the user is authenticated, the middleware allows the request to proceed to the route handler. If the user is not authenticated, the middleware may redirect the user to a login page, return an error response, or take other appropriate actions. Before we look at actually creating the authMiddleware, we need to briefly discuss the different authentication strategies.

Authentication Strategies

Although there are several strategies to use when authenticating, such as OAuth2, or Passport, for simplicity we will use the express-session (session). Please refer to the link on how to properly setup session in your environment.

Create Authentication Middleware

First, we need to create a middleware function that will handle the authentication logic. The middleware function typically checks for the presence of authentication data, in our case: session. As I quoted from expressjs.com earlier, middleware functions have access to the req, res objects as well as the next function. The next function (called 'next' by convention)(expressjs.com) is a callback provided by Express that allows a middleware function to pass control to the next middleware or route handler in the chain. When called, it passes the request to the next function and continues the execution flow through the middleware stack. If next is not called within a middleware, the request might hang, and subsequent middleware or route handlers won't be executed.

// in a separate location: ../middlewares/authentication.js

const authMiddleware = (req, res, next) => {
 // Check if the user has an active session
 if (req.session && req.session.user) {
  next();
 } else { 
  //User does not have an active session, redirect to login page
  res.redirect('/login');
 }
};

module.exports = authMiddleware;
Enter fullscreen mode Exit fullscreen mode

This middleware checks if the user has an active session (indicating that they are authenticated) before allowing access to protected routes. If the user doesn't have an active session, they are redirected to a login page. In this example, we assume that the req.session.user object contains user information after a successful login. When the user logs in with the correct credentials, we would set req.session.user with the necessary user data (e.g. username, user_id) during the login process.

Implementing the Middleware

Now that we have our bouncer created, we next need to include it in any and all routes that require a VIP badge. First, let's take a look at the syntax for a standard GET request:

const express = require('express');
const router = express.Router();

router.get('/VIPdata', (req, res) => {
 res.render('vipData');
});
module.exports = router;
Enter fullscreen mode Exit fullscreen mode

This code sets up an ExpressJS server that listens for GET requests on the URL route '/VIPdata'. When a request is made, the server responds by rendering the 'vipData' page. Anyone will be able to walk into the VIP section and view your data!

Now, let's look at the syntax for adding our middleware. Although we could have used a nameless function inside the GET request, best practices for DRY code would be to establish a named function, then require it in any routes that will need it.

const express = require('express');
const router = express.Router();
const authMiddleware = require('../middlewares/authentication');

// Our middleware sits between the route, and the route logic
router.get('/VIPdata', authMiddleware, (req, res) => {
 res.render('vipData');
});

module.exports = router;

Enter fullscreen mode Exit fullscreen mode

The route is now protected with our authentication middleware (imported as authMiddleware) to ensure only authenticated users can access it. When a request is made to '/VIPdata', the server renders the 'vipData' view, allowing authenticated users to access the protected VIP data.

Conclusion:

In conclusion, we've journeyed into the fascinating realm of authentication middleware in ExpressJS, where we discovered the power of these "bouncers" guarding our web applications. Just like vigilant sentinels, authentication middleware ensures that only trusted users gain access to the exclusive parts of our application. Armed with these valuable insights, we're now equipped to protect our web applications with confidence, allowing users to revel in the unique and personalized experiences they deserve. So go forth, embrace the power of authentication middleware, and let your Express applications shine with a heightened sense of security and user satisfaction!
-Josh

Top comments (0)