How to write Express.js middleware with TypeScript

Table of contents

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'

;


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'

);

app.

use

(preventCrossSiteScripting);
}