Middleware Implementation

Tutorial 2 of 4

1. Introduction

This tutorial aims to provide a comprehensive guide on how to implement middleware in Express.js. Middleware is a crucial component in Express.js that allows you to execute any code, make changes to the request and response objects, end the request-response cycle, or call the next middleware function in the stack.

By the end of this tutorial, you will:

  • Understand what middleware is and how it operates in Express.js
  • Know how to implement middleware in your Express.js applications
  • Gain practical experience through code examples and exercises

Before we begin, ensure you have a basic understanding of JavaScript and Node.js. Also, you should have Node.js and Express.js installed on your machine.

2. Step-by-Step Guide

Middleware functions 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, denoted as next.

Middleware functions can:

  • Execute any code.
  • Make changes to the request and the response objects.
  • End the request-response cycle.
  • Call the next middleware function 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.

2.1 Application-Level Middleware

Here's how to define an application-level middleware with Express.js.

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

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

In this example, the middleware function is invoked every time the app receives a request. The next() function is called to pass control to the next middleware function.

2.2 Router-Level Middleware

Router-level middleware works in the same way as application-level middleware, but it is bound to an instance of express.Router().

var express = require('express')
var router = express.Router()

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

3. Code Examples

3.1 Application-Level Middleware

Here's a practical example of application-level middleware that prints the current time and request method for each HTTP request.

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

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

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

app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
})

3.2 Router-Level Middleware

This example demonstrates router-level middleware that logs the request method and URL.

var express = require('express')
var router = express.Router()

router.use(function (req, res, next) {
  console.log('Request Type:', req.method)
  console.log('Request URL:', req.originalUrl)
  next()
})

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

app.use('/', router)

app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
})

4. Summary

In this tutorial, you learned what middleware is, how it works in Express.js, and how to implement it in your applications. You also worked through practical examples of both application-level and router-level middleware.

To continue learning about Express.js middleware, you can explore error-handling middleware, built-in middleware, and third-party middleware.

5. Practice Exercises

  1. Create an Express.js application that uses middleware to log the request method, URL, and current time for every HTTP request.

  2. Create an Express.js application that uses middleware to modify the request object, adding a new property req.timestamp with the current time.

  3. Create an Express.js application that uses middleware to handle 404 errors. The middleware should respond with a custom error message.

Remember, the key to mastering middleware (and Express.js in general) is through consistent practice and application of the concepts. Happy coding!