Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Creating Custom Middleware | Middleware in Express.js
Express.js Essentials for Backend Development

Creating Custom Middleware

Swipe to show menu

When you want your Express.js application to enforce certain rules or perform checks on incoming requests, you can write custom middleware functions. For instance, you might want to ensure that every request includes a specific header before it reaches your route handlers. Below is a custom middleware example that checks for a header called "x-api-key". If the header is missing, the middleware sends a response with a 400 Bad Request status and a message; otherwise, it allows the request to proceed.

function checkApiKey(req, res, next) {
  const apiKey = req.headers['x-api-key'];
  if (!apiKey) {
    return res.status(400).json({ error: 'Missing x-api-key header' });
  }
  next();
}

This middleware inspects the incoming request’s headers for the "x-api-key". If the header is not present, it immediately stops request processing and sends a JSON error response. If the header exists, it calls next() to pass control to the next middleware or route handler.

To understand how this middleware works and how to use it, follow these steps:

  1. Define the middleware function, such as checkApiKey, with the parameters req, res, and next;
  2. Inside the function, access the request headers using req.headers['x-api-key'];
  3. If the header is missing, respond with res.status(400).json({ error: 'Missing x-api-key header' }) and return to stop further processing;
  4. If the header is present, call next() to continue to the next middleware or route;
  5. Integrate your custom middleware into your Express app by passing it to app.use() or as a parameter to specific routes:
const express = require('express');
const app = express();

function checkApiKey(req, res, next) {
  const apiKey = req.headers['x-api-key'];
  if (!apiKey) {
    return res.status(400).json({ error: 'Missing x-api-key header' });
  }
  next();
}

// Apply middleware globally
app.use(checkApiKey);

app.get('/protected', (req, res) => {
  res.send('Access granted!');
});

app.listen(3000);

By following these steps, your custom middleware will intercept requests and enforce the presence of the required header before any protected route logic runs.

question mark

Which of the following best describes the process of creating and using a custom middleware function in Express.js?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 3. Chapter 3

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

Section 3. Chapter 3
some-alt