0
0
NestJSframework~30 mins

Applying middleware to routes in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Applying middleware to routes in NestJS
📖 Scenario: You are building a simple NestJS server that logs requests to certain routes. Middleware helps you run code before the route handler runs, like logging or checking permissions.
🎯 Goal: Create a NestJS middleware that logs a message for requests, then apply it only to the /cats route.
📋 What You'll Learn
Create a middleware class called LoggerMiddleware that logs 'Request received' when a request comes in.
Create a controller called CatsController with a GET route at /cats that returns a simple string.
Apply the LoggerMiddleware only to the /cats route using the configure method in the main module.
Ensure the middleware runs before the route handler and logs the message.
💡 Why This Matters
🌍 Real World
Middleware is used in real web servers to add logging, security checks, or modify requests before they reach the main route handlers.
💼 Career
Understanding middleware application is essential for backend developers working with NestJS or similar frameworks to build scalable and maintainable server applications.
Progress0 / 4 steps
1
Create the LoggerMiddleware class
Create a class called LoggerMiddleware that implements NestMiddleware. Inside the use method, log the string 'Request received' and call next().
NestJS
Need a hint?

Remember to import NestMiddleware and implement the use method with req, res, and next parameters.

2
Create the CatsController with a GET /cats route
Create a controller class called CatsController with a @Controller('cats') decorator. Add a GET route method called findAll that returns the string 'This action returns all cats'.
NestJS
Need a hint?

Use the @Controller('cats') decorator and add a method with @Get() that returns the required string.

3
Apply LoggerMiddleware only to the /cats route
In the main module class called AppModule, implement the configure method. Use consumer.apply(LoggerMiddleware).forRoutes('cats') to apply the middleware only to the /cats route.
NestJS
Need a hint?

Implement NestModule and use the configure method to apply middleware to the 'cats' route.

4
Complete the module with imports and exports
Add the LoggerMiddleware to the providers array in @Module so NestJS can inject it properly.
NestJS
Need a hint?

Add LoggerMiddleware to the providers array inside the @Module decorator.