Express.js / Express.js Basics

Understanding Middleware in Express

Middleware is a fundamental concept in Express.js. In this tutorial, you will learn what middleware is, how it works, and how you can use it in your Express applications.

Tutorial 4 of 5 5 resources in this section

Section overview

5 resources

Covers the fundamental concepts of Express.js, including installation, setup, and creating a basic application.

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.

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 Password Generator

Create secure, complex passwords with custom length and character options.

Use tool

Hex to Decimal Converter

Convert between hexadecimal and decimal values.

Use tool

Random Name Generator

Generate realistic names with customizable options.

Use tool

Watermark Generator

Add watermarks to images easily.

Use tool

PDF Password Protector

Add or remove passwords from PDF files.

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