📖 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
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
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
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
Hint
Register the middleware class in the providers array inside the @Module decorator.
Practice
(1/5)
1. What is the main purpose of middleware in a NestJS application?
easy
A. To handle server errors automatically
B. To define database models
C. To run code before the request reaches the route handler
D. To create UI components
Solution
Step 1: Understand middleware role
Middleware is code that runs before the main route handler processes a request.
Step 2: Compare options
Only To run code before the request reaches the route handler describes this behavior correctly; others describe unrelated tasks.
Final Answer:
To run code before the request reaches the route handler -> Option C
Quick Check:
Middleware runs before routes [OK]
Hint: Middleware always runs before route handlers [OK]
Common Mistakes:
Confusing middleware with controllers
Thinking middleware handles UI rendering
Assuming middleware manages database models
2. Which of the following is the correct way to define a middleware class in NestJS?
B. class MyMiddleware { handle(req, res, next) { next(); } }
C. function MyMiddleware(req, res, next) { next(); }
D. class MyMiddleware { use(req, res, next) { next(); } }
Solution
Step 1: Recall NestJS middleware pattern
Middleware must be a class with a method named use that takes req, res, next.
Step 2: Check options
Only class MyMiddleware { use(req, res, next) { next(); } } defines a class with a use method correctly. class MyMiddleware { handle(req, res, next) { next(); } } uses handle, which is invalid. Options C and D define functions, not classes.
Final Answer:
class MyMiddleware { use(req, res, next) { next(); } } -> Option D
Quick Check:
Middleware class must have use() method [OK]
Hint: Middleware class must have a use() method [OK]
Common Mistakes:
Using method name other than use
Defining middleware as a function instead of class
Forgetting to call next() inside use
3. Given this middleware class, what will be logged when a request to '/some-path' hits the route?
In NestJS, you can specify route and HTTP method using an object with path and method in forRoutes.
Step 2: Evaluate options
Use consumer.apply(MyMiddleware).forRoutes({ path: '/login', method: RequestMethod.POST }) correctly uses { path: '/login', method: RequestMethod.POST }. Use consumer.apply(MyMiddleware).forRoutes('/login') and check method inside middleware applies middleware to all methods on '/login', requiring manual filtering. Apply middleware globally and filter POST requests inside middleware applies globally, which is less efficient. NestJS does not support method-specific middleware is false.
Final Answer:
Use consumer.apply(MyMiddleware).forRoutes({ path: '/login', method: RequestMethod.POST }) -> Option B
Quick Check:
Use forRoutes with path and method object [OK]
Hint: Use forRoutes with path and method object for specific HTTP verbs [OK]
Common Mistakes:
Applying middleware to all methods unintentionally
Not importing RequestMethod enum
Assuming method-specific middleware is unsupported
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.