Express.js / Routing in Express.js

Middleware Implementation

This tutorial will guide you through the process of implementing middleware in Express.js. You will learn what middleware is, how it works, and how to use it in your applications.

Tutorial 2 of 4 4 resources in this section

Section overview

4 resources

Explores handling routes, route parameters, and query strings in Express applications.

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!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Random String Generator

Generate random alphanumeric strings for API keys or unique IDs.

Use tool

Random Number Generator

Generate random numbers between specified ranges.

Use tool

Image Compressor

Reduce image file sizes while maintaining quality.

Use tool

Timestamp Converter

Convert timestamps to human-readable dates.

Use tool

Text Diff Checker

Compare two pieces of text to find differences.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help