0
0
NestJSframework~30 mins

Middleware ordering in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Middleware Ordering in NestJS
📖 Scenario: You are building a simple NestJS application that logs requests and checks authentication. The order of middleware matters because logging should happen before authentication.
🎯 Goal: Create two middleware functions: one for logging requests and one for authentication. Apply them in the correct order so that logging runs before authentication for all routes.
📋 What You'll Learn
Create a logging middleware function named loggerMiddleware that logs the request method and URL.
Create an authentication middleware function named authMiddleware that checks for a header x-auth-token and rejects requests without it.
Apply both middleware functions globally in the correct order: loggerMiddleware first, then authMiddleware.
Use NestJS middleware consumer and configure method in the main app module.
💡 Why This Matters
🌍 Real World
Middleware ordering is important in web applications to ensure tasks like logging, authentication, and validation happen in the correct sequence.
💼 Career
Understanding middleware and its order is essential for backend developers working with NestJS or similar frameworks to build secure and maintainable APIs.
Progress0 / 4 steps
1
Create the logging middleware function
Create a middleware function called loggerMiddleware that logs the HTTP method and URL of each request using console.log. The function should accept req, res, and next parameters and call next() at the end.
NestJS
Need a hint?

Middleware functions in NestJS receive req, res, and next. Use console.log to print the method and URL.

2
Create the authentication middleware function
Create a middleware function called authMiddleware that checks if the request header x-auth-token exists. If it does not exist, respond with status 401 and message 'Unauthorized'. Otherwise, call next().
NestJS
Need a hint?

Check the header x-auth-token in req.headers. If missing, send a 401 response. Otherwise, call next().

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

Use consumer.apply() with both middleware functions in the correct order, then call forRoutes('*') to apply globally.

4
Export middleware functions and finalize module
Add export keywords before loggerMiddleware and authMiddleware functions so they can be imported elsewhere if needed. Ensure the AppModule class is exported as well.
NestJS
Need a hint?

Use export before the middleware functions and the AppModule class to make them available outside this file.