Express middleware

Express also allows us to declare a middleware function. A middleware function allows us to implement cross-cutting concerns. A cross-cutting concern is a requirement that affects the entire application or a subset of it. Common examples of cross-cutting concerns are logging and authorization.

A middleware function takes the current request and response as arguments together with a function known as next:

const middlewareFunction = ( 
    req: express.Request, 
    res: express.Response, 
    next: express.NextFunction 
) => { 
    next(); 
}; 

We can chain middleware functions, and the next function is what communicates to Express that the middleware has finished its task and the next middleware can be invoked. When no more middleware functions ...

Get Learning TypeScript 2.x - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.