0
0
Node.jsframework~5 mins

Building custom middleware in Node.js

Choose your learning style9 modes available
Introduction

Middleware helps you add extra steps when your server handles requests. It lets you run code before sending a response.

You want to check if a user is logged in before showing a page.
You need to log details about every request your server gets.
You want to add special headers to all responses.
You want to handle errors in one place for all requests.
Syntax
Node.js
function middlewareName(req, res, next) {
  // Your code here
  next();
}

The req is the request object with info about the client request.

The res is the response object used to send data back.

The next is a function you call to move to the next middleware or route.

Examples
This middleware logs the HTTP method and URL of each request.
Node.js
function logger(req, res, next) {
  console.log(`${req.method} ${req.url}`);
  next();
}
This middleware adds a custom header to every response.
Node.js
function addPoweredBy(req, res, next) {
  res.setHeader('X-Powered-By', 'Node.js');
  next();
}
This middleware checks if the request has an authorization header and blocks access if missing.
Node.js
function checkAuth(req, res, next) {
  if (!req.headers.authorization) {
    res.status(401).send('Unauthorized');
  } else {
    next();
  }
}
Sample Program

This example creates a simple Express server. It uses a custom middleware called logger that prints the HTTP method and URL for every request. Then it responds with 'Hello, world!' on the home page.

Node.js
import express from 'express';

const app = express();

// Custom middleware to log requests
function logger(req, res, next) {
  console.log(`${req.method} ${req.url}`);
  next();
}

// Use the middleware for all routes
app.use(logger);

app.get('/', (req, res) => {
  res.send('Hello, world!');
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
OutputSuccess
Important Notes

Always call next() in your middleware unless you send a response directly.

Middleware runs in the order you add it with app.use() or on routes.

You can create middleware to handle errors by defining a function with four arguments: (err, req, res, next).

Summary

Middleware lets you add extra steps when handling requests.

It uses three arguments: req, res, and next.

Call next() to continue to the next step or send a response to end.