0
0
NestJSframework~30 mins

Functional middleware in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Functional Middleware in NestJS
📖 Scenario: You are building a simple NestJS server that logs requests. Middleware helps you run code before your route handlers. Functional middleware is a simple function that can log info about each request.
🎯 Goal: Create a functional middleware in NestJS that logs the HTTP method and URL of each incoming request.
📋 What You'll Learn
Create a functional middleware function named loggerMiddleware
Use the req, res, and next parameters in the middleware
Log the HTTP method and URL using console.log
Call next() to pass control to the next middleware or route handler
Apply the middleware to a simple NestJS AppModule using configure method
💡 Why This Matters
🌍 Real World
Middleware is used in real web servers to handle tasks like logging, authentication, and error handling before requests reach the main logic.
💼 Career
Understanding functional middleware is essential for backend developers working with NestJS or similar frameworks to build scalable and maintainable server applications.
Progress0 / 4 steps
1
Create the functional middleware
Create a function called loggerMiddleware that takes req, res, and next as parameters.
NestJS
Need a hint?

Middleware functions always have three parameters: req, res, and next.

2
Add logging inside the middleware
Inside the loggerMiddleware function, add a console.log statement that logs the HTTP method and URL from req.method and req.url. Then call next().
NestJS
Need a hint?

Use template strings to combine req.method and req.url in the log.

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

The configure method receives a consumer to apply middleware.

4
Complete the NestJS server setup
Add the necessary imports for NestFactory from @nestjs/core. Create an async bootstrap function that creates the app with NestFactory.create(AppModule) and listens on port 3000. Call bootstrap().
NestJS
Need a hint?

Use await with NestFactory.create and app.listen inside an async function.