Creating Custom Middleware Functions

Tutorial 2 of 5

Creating Custom Middleware Functions

Introduction

In this tutorial, we will dive into the world of Express.js to understand and implement custom middleware functions. 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. The next function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware.

By the end of this tutorial, you will have a fundamental understanding of how to create and use your own custom middleware in Express.js.

Prerequisites: Basic understanding of JavaScript and Node.js is required. Experience with Express.js can be helpful but not necessary.

Step-by-Step Guide

Middleware functions can perform the following tasks:

  • Execute any code.
  • Make changes to the request and the response objects.
  • End the request-response cycle.
  • Call the next middleware in the stack.

Let's create a simple middleware function that logs the current date and time on each request.

function logDateTime(req, res, next) {
  console.log('Time:', Date.now())
  next()
}

Here, req is the request object, res is the response object, and next is a callback function that we call to pass control to the next middleware function. If we don't call next(), the request will be left hanging.

We can use this middleware in our application with app.use():

var express = require('express')
var app = express()

app.use(logDateTime)

app.get('/', function (req, res) {
  res.send('Hello World!')
})

app.listen(3000)

Now, every time our app receives a request, it will print the current date and time to the console.

Code Examples

Example 1: A middleware that logs the method and URL of the request.

function logRequestDetails(req, res, next) {
  console.log(`Method: ${req.method}, URL: ${req.url}`);
  next();
}

app.use(logRequestDetails);

Example 2: A middleware that checks if a user is authenticated.

function isAuthenticated(req, res, next) {
  if (req.isAuthenticated()) {
    next();
  } else {
    res.redirect('/login');
  }
}

app.get('/dashboard', isAuthenticated, function(req, res) {
  res.send('Welcome to your dashboard!');
});

In this example, if the user is authenticated, we call next() and continue to the route handler. If they're not authenticated, we redirect them to the login page.

Summary

In this tutorial, we learned how to create and use custom middleware functions in Express.js. We saw that middleware functions can execute any code, make changes to the request and response objects, end the request-response cycle, and call the next middleware in the stack.

Going forward, you can start using custom middleware to handle authentication, logging, error handling, and more in your Express.js applications.

Here are some additional resources to learn more about Express.js middleware:

Practice Exercises

  1. Create a middleware function that adds a user object to the request if a user is logged in.
  2. Create a middleware function that logs the response status code when the response is sent.
  3. Create a middleware function that checks if a user is an admin before allowing them to access a route.

Happy coding!