Express.js / Middleware in Express.js

Creating Custom Middleware Functions

In this tutorial, we will learn how to create and use custom middleware functions in Express.js applications.

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Covers the role of middleware in Express and its different types.

Creating Custom Middleware Functions

Introduction

In this tutorial, we will dive into the world of Express.js to understand and implement custom middleware functions. 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.

By the end of this tutorial, you will have a fundamental understanding of how to create and use your own custom middleware in Express.js.

Prerequisites: Basic understanding of JavaScript and Node.js is required. Experience with Express.js can be helpful but not necessary.

Step-by-Step Guide

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.

Let's create a simple middleware function that logs the current date and time on each request.

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

Here, req is the request object, res is the response object, and next is a callback function that we call to pass control to the next middleware function. If we don't call next(), the request will be left hanging.

We can use this middleware in our application with app.use():

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

app.use(logDateTime)

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

app.listen(3000)

Now, every time our app receives a request, it will print the current date and time to the console.

Code Examples

Example 1: A middleware that logs the method and URL of the request.

function logRequestDetails(req, res, next) {
  console.log(`Method: ${req.method}, URL: ${req.url}`);
  next();
}

app.use(logRequestDetails);

Example 2: A middleware that checks if a user is authenticated.

function isAuthenticated(req, res, next) {
  if (req.isAuthenticated()) {
    next();
  } else {
    res.redirect('/login');
  }
}

app.get('/dashboard', isAuthenticated, function(req, res) {
  res.send('Welcome to your dashboard!');
});

In this example, if the user is authenticated, we call next() and continue to the route handler. If they're not authenticated, we redirect them to the login page.

Summary

In this tutorial, we learned how to create and use custom middleware functions in Express.js. We saw that middleware functions can execute any code, make changes to the request and response objects, end the request-response cycle, and call the next middleware in the stack.

Going forward, you can start using custom middleware to handle authentication, logging, error handling, and more in your Express.js applications.

Here are some additional resources to learn more about Express.js middleware:

Practice Exercises

  1. Create a middleware function that adds a user object to the request if a user is logged in.
  2. Create a middleware function that logs the response status code when the response is sent.
  3. Create a middleware function that checks if a user is an admin before allowing them to access a route.

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

Age Calculator

Calculate age from date of birth.

Use tool

PDF Compressor

Reduce the size of PDF files without losing quality.

Use tool

Watermark Generator

Add watermarks to images easily.

Use tool

Case Converter

Convert text to uppercase, lowercase, sentence case, or title case.

Use tool

JSON Formatter & Validator

Beautify, minify, and validate JSON data.

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