ยท hands on

How to write Express.js middleware with TypeScript

You can extend your Express.js server by writing custom middleware functions. These functions intercept every request and allow you to add custom functionality or filters. You can also pass the request to other middleware functions.

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).

Contents

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

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);
}
Back to Blog