Table of contents

  1. 1. Writing custom Express middleware

You can extend your Express.js server easily with custom middleware. All you have to do is to write a function that accepts three parameters (req, res, next).

Writing custom Express middleware

By writing a function that follows the ApplicationRequestHandler type of Express.js, you can extend your app server with custom functionality.

A “middleware” in Express is just a function that intercepts every request so that you can return a custom response or apply a custom filter when a request reaches your server. You can also call the next function to pass on the request for processing (to another registered middleware).

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
import {Express, Request, Response, NextFunction} from 'express';

// Your custom "middleware" function:
function preventCrossSiteScripting(req: Request, res: Response, next: NextFunction): void {
res.setHeader('X-XSS-Protection', '1; mode=block');
next();
}

export function applyServerHardening(app: Express): void {
app.disable('x-powered-by');
// Make your Express app use your custom middleware:
app.use(preventCrossSiteScripting);
}