0
0
NestJSframework~30 mins

Creating middleware in NestJS - Try It Yourself

Choose your learning style9 modes available
Creating middleware
📖 Scenario: You are building a simple NestJS application that needs to log every request's method and URL. Middleware is a perfect place to do this because it runs before the route handlers.
🎯 Goal: Create a middleware in NestJS that logs the HTTP method and URL of each incoming request.
📋 What You'll Learn
Create a middleware class named LoggerMiddleware
Implement the use method inside LoggerMiddleware
Log the request method and URL inside the use method
Apply the middleware to all routes in the main application module
💡 Why This Matters
🌍 Real World
Middleware is used in real web applications to handle tasks like logging, authentication, and request validation before the main route logic runs.
💼 Career
Understanding middleware is essential for backend developers working with NestJS or similar frameworks, as it helps manage cross-cutting concerns cleanly.
Progress0 / 4 steps
1
Create the LoggerMiddleware class
Create a class called LoggerMiddleware that implements NestMiddleware from @nestjs/common. Inside it, define an empty use method that takes req, res, and next as parameters.
NestJS
Need a hint?

Remember to import NestMiddleware and the types Request, Response, and NextFunction from Express.

2
Add logging inside the use method
Inside the use method of LoggerMiddleware, add a console.log statement that logs the HTTP method and URL of the incoming request using req.method and req.url. Then call next() to continue the request cycle.
NestJS
Need a hint?

Use a template string to include req.method and req.url inside the log message.

3
Apply the LoggerMiddleware in the AppModule
In the AppModule class, implement the configure method that takes a MiddlewareConsumer parameter. Use consumer.apply(LoggerMiddleware).forRoutes('*') to apply the middleware to all routes.
NestJS
Need a hint?

Use the configure method and MiddlewareConsumer to apply middleware globally.

4
Complete the module imports and exports
Add LoggerMiddleware to the providers array in the @Module decorator of AppModule to register it properly.
NestJS
Need a hint?

Register the middleware class in the providers array inside the @Module decorator.