Understanding Middleware in Express.js

Tutorial 1 of 5

Understanding Middleware in Express.js

1. Introduction

In this tutorial, we will demystify the concept of middleware in Express.js. Middleware is a fundamental concept in Express.js that every web developer should understand. By the end of this tutorial, you will understand what middleware is, how it works, and why it is used in Express.js.

What You Will Learn

  • What is middleware in Express.js?
  • How does middleware work?
  • Why and when should you use middleware?

Prerequisites

  • Basic knowledge of JavaScript and Node.js
  • Basic understanding of how Express.js works

2. Step-by-Step Guide

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.

function(req, res, next) {
  // Middleware code here
}

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.

If the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function. Otherwise, the request will be left hanging.

3. Code Examples

Example 1: Logging Middleware

Here's an example of a basic logging middleware function that logs the method and url of the request:

// Logging middleware
app.use(function (req, res, next) {
  console.log(`${req.method} ${req.url}`);
  next(); // Call next to move to the next middleware
});

In the above code, app.use() is used to load the middleware function. The middleware function takes 3 parameters: req (the request object), res (the response object), and next (a function to call the next middleware). The middleware logs the method and url of the request, then calls next() to pass control to the next middleware.

Example 2: Middleware that Modifies the Request Object

Middleware can also modify the request or response objects. Here's an example that adds a property called 'timestamp' to the request object:

// Middleware that adds a timestamp to the request
app.use(function (req, res, next) {
  req.timestamp = Date.now();
  next();
});

app.get('/', function (req, res) {
  res.send(`Request timestamp: ${req.timestamp}`); // Use the timestamp
});

In this example, the middleware adds a timestamp to the request object, then passes control to the next middleware. The route handler for '/' then sends a response that includes the timestamp.

4. Summary

In this tutorial, you've learned about middleware in Express.js. Middleware are functions that can access and modify the request and response objects, and can control when the next middleware is called. They're used for a wide variety of tasks, such as logging, error handling, and adding additional functionality to the request/response objects.

5. Practice Exercises

Exercise 1

Write a middleware function that logs the current date and time each time a request is made to the server.

Solution

app.use(function (req, res, next) {
  console.log(`Current date and time: ${new Date()}`);
  next();
});

Exercise 2

Write a middleware function that checks if a 'username' property exists on the request object. If it doesn't, add one with a value of 'Guest'.

Solution

app.use(function (req, res, next) {
  if (!req.username) {
    req.username = 'Guest';
  }
  next();
});

Keep practicing and exploring more about Express.js middleware. Remember, the more you use middleware in your applications, the more you'll understand and appreciate their power and flexibility.