Middleware in TypeScript
Middleware is a function that is executed before an HTTP request is handled by a route handler. It is commonly used to perform tasks such as authentication, logging, or data validation.
Here is an example of how you could create a middleware function in TypeScript:
import { Request, Response, NextFunction } from 'express';
function loggerMiddleware(req: Request, res: Response, next: NextFunction) {
console.log(`${req.method} request made to ${req.path}`);
next();
}
This middleware function logs the HTTP method and path of each request made to the server. The next
function is called to pass the request on to the next middleware function or route handler in the chain.
To use this middleware function in your Express app, you will need to pass it as an argument to the app.use()
method:
app.use(loggerMiddleware);
You can also pass the middleware function to a specific route:
app.get('/users', loggerMiddleware, (req, res) => {
// route handler code goes here
});
You can also create middleware functions that take arguments, such as a custom error handler:
function errorHandlerMiddleware(err: any, req: Request, res: Response, next: NextFunction) {
console.error(err);
res.status(500).send('Something went wrong');
}
app.use(errorHandlerMiddleware);
This middleware function logs the error and sends a response with a status code of 500 and a message to the client.
You can use middleware functions to perform a variety of tasks in your Express app, and they can be a powerful tool for organizing and reusing code.