Understanding Middleware in Express

Tutorial 4 of 5

Understanding Middleware in Express

1. Introduction

In this tutorial, we will be exploring the concept of middleware in Express.js, a popular and robust web application framework for Node.js. By the end of this tutorial, you will have a solid understanding of what middleware is, how it works, and how to effectively use it in your Express applications.

Prerequisites: Basic knowledge of JavaScript, Node.js and Express.js will be beneficial.

2. Step-by-Step Guide

Middleware are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. These functions can execute any code, make changes to the request and the response objects, end the request-response cycle, and call the next middleware function in the stack.

Here is a basic example:

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

In this example, the middleware logs the current time, and then passes control to the next middleware function using the next() function.

Best practices and tips:

  • Always call next() unless your middleware is meant to terminate the request-response cycle. If you don't, the request will hang and not proceed to the next middleware or route handler.
  • Middleware is executed in the order it is added with app.use(). Be mindful of the order in which you add middleware to your application.

3. Code Examples

Here are some more examples of middleware in action:

Example 1: Middleware function that logs the URL and the date of each request.

app.use(function (req, res, next) {
  console.log('Request URL:', req.originalUrl)
  console.log('Time:', Date.now())
  next()
})

In this example, req.originalUrl contains the original URL path of the request and Date.now() gives the current time in milliseconds since 1970.

Example 2: Middleware function that authenticates a user

app.use(function (req, res, next) {
  if (req.isAuthenticated()) {
    return next()
  }
  res.redirect('/login')
})

In this example, if the user is authenticated, the middleware calls next(), allowing the request to proceed to the next middleware or route handler. If the user is not authenticated, the middleware sends a response to redirect the user to the login page.

Expected Output: These middleware functions don't have an output that can be directly seen, but you can observe their effects (logging to the console, redirecting the user) when you make requests to your Express app.

4. Summary

In this tutorial, we have learned about middleware in Express.js. We learned that middleware are functions that have access to the request and response objects, and can execute any code, modify the request and response, end the request-response cycle, or pass control to the next middleware function.

Your next steps might include learning about built-in middleware in Express, like express.static, or third-party middleware like body-parser and cors.

Some additional resources include the Express.js documentation on middleware.

5. Practice Exercises

  1. Create a middleware function that logs the method of each request (GET, POST, etc.).
  2. Create a middleware function that sends a custom error response if a request is made to a non-existing route.

Solutions:

  1. Here's a middleware that logs the method of each request:
app.use(function (req, res, next) {
  console.log('Request Method:', req.method)
  next()
})
  1. Here's a middleware that sends a custom error response for non-existing routes:
app.use(function (req, res, next) {
  res.status(404).send('Sorry, that route does not exist.')
})

Note that this middleware does not call next(), because it's meant to end the request-response cycle when a non-existing route is requested.

For further practice, try building your own Express app and experiment with adding different middleware functions.