0
0
NestJSframework~30 mins

Why middleware processes requests before handlers in NestJS - See It in Action

Choose your learning style9 modes available
Understanding Middleware Processing Order in NestJS
📖 Scenario: You are building a simple NestJS server that logs request details before handling them. This helps you understand how middleware works before the main request handler.
🎯 Goal: Create a NestJS middleware that logs the request method and URL before the request reaches the handler.
📋 What You'll Learn
Create a middleware function named LoggerMiddleware
Configure the middleware to apply to all routes
Log the HTTP method and URL of each incoming request
Create a simple controller with a GET handler at path /hello that returns a greeting
💡 Why This Matters
🌍 Real World
Middleware is used in real web servers to log requests, check user authentication, and modify requests before they reach the main logic.
💼 Career
Understanding middleware is essential for backend developers working with NestJS or similar frameworks to build secure and maintainable server applications.
Progress0 / 4 steps
1
Create a simple controller with a GET handler
Create a controller class named HelloController with a method getHello that handles GET requests at path /hello and returns the string 'Hello, NestJS!'.
NestJS
Need a hint?

Use @Controller() and @Get('hello') decorators to define the route and handler.

2
Create a middleware class named LoggerMiddleware
Create a class named LoggerMiddleware that implements NestMiddleware and has a use method accepting req, res, and next parameters.
NestJS
Need a hint?

Import NestMiddleware and Injectable from @nestjs/common. Define the use method with parameters req, res, and next.

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

Use a template string inside console.log to show req.method and req.url.

4
Apply the LoggerMiddleware globally in the main module
In the main application module, import MiddlewareConsumer and Module from @nestjs/common. Then, in the AppModule class, implement the configure method that accepts a consumer parameter of type MiddlewareConsumer. Use consumer.apply(LoggerMiddleware).forRoutes('*') to apply the middleware to all routes.
NestJS
Need a hint?

Use the configure method in AppModule to apply middleware globally with consumer.apply(...).forRoutes('*').