Middlewares and Guards
We'll cover setting up Middlewares and Guards, applying them to routes, and ensuring your code adheres to SOLID principles for maintainability and scalability.
Introduction to Middlewares and Guards
Middlewares and Guards are fundamental components in NestJS that help manage request processing and authorization.
Middlewares: Functions that execute before the route handler, allowing you to manipulate the request and response objects. Common use cases include logging, authentication, and request validation.
Guards: Provide a way to control access to route handlers based on specific conditions. They are typically used for authorization, ensuring that only authenticated or authorized users can access certain endpoints.
Integrating Middlewares and Guards effectively enhances the security, maintainability, and scalability of your NestJS applications.
Setting Up Middlewares in NestJS
Step 1: Create a Middleware
To create a Middleware in NestJS, you can use the Nest CLI or manually create the necessary files.
Using Nest CLI:
This command generates a logger.middleware.ts
file in the src
directory.
Manual Creation:
Create a new directory for middlewares if it doesn't exist:
Example: Logger Middleware
Explanation:
@Injectable()
: Marks the class as a provider that can be injected into other classes.NestMiddleware
: Interface that requires theuse
method.use
Method: ReceivesRequest
,Response
, andNextFunction
objects. It logs request details and callsnext()
to pass control to the next middleware or route handler.
Step 2: Apply Middleware to Routes
Middlewares can be applied globally or to specific routes/modules.
Global Middleware:
To apply a middleware globally, modify the main.ts
file.
Specific Middleware:
To apply middleware to specific routes, configure it within a module.
Example: Applying Middleware in AppModule
Explanation:
MiddlewareConsumer
: Provides methods to apply middlewares to routes.apply
Method: Specifies which middleware to apply.forRoutes
Method: Defines the routes where the middleware should be applied. In this example, theLoggerMiddleware
is applied to all methods (RequestMethod.ALL
) on theusers
route.
Step 3: Configuring Middleware for Specific Routes
You can apply middlewares to multiple routes or controllers as needed.
Example: Applying Middleware to Multiple Routes
Explanation:
The
LoggerMiddleware
is now applied to bothusers
andproducts
routes, logging requests for both.
Creating Guards in NestJS
Guards are used to determine whether a request should be handled by the route handler or not based on specific conditions, such as user authentication and authorization.
Step 1: Create a Guard
You can create a Guard using the Nest CLI or manually.
Using Nest CLI:
This command generates an auth.guard.ts
file in the src
directory.
Manual Creation:
Create a new directory for guards if it doesn't exist:
Example: Auth Guard
Explanation:
@Injectable()
: Marks the class as a provider.CanActivate
: Interface that requires thecanActivate
method.canActivate
Method: Determines whether the request should proceed. It extracts the token from the request header and validates it using anAuthService
.AuthService
: A hypothetical service responsible for token verification. Ensure you have this service implemented.
Step 2: Apply Guards to Controllers and Routes
Guards can be applied at various levels: method, controller, or globally.
Applying Guard to a Controller:
Applying Guard to a Specific Route:
Explanation:
@UseGuards(AuthGuard)
: Applies theAuthGuard
to the controller or specific route, ensuring that only authenticated requests can access the endpoint.
Step 3: Global Guards
To apply a Guard globally across all routes and controllers, configure it in the main.ts
file.
Example: Applying Auth Guard Globally
Explanation:
useGlobalGuards
: Applies the specified Guard to all routes within the application.app.get(AuthGuard)
: Retrieves an instance of theAuthGuard
from the application's dependency injection container.
Using Middlewares and Guards Together
Middlewares and Guards can complement each other to provide comprehensive request processing and security.
Example: Combining Logger Middleware and Auth Guard
Logger Middleware: Logs every incoming request.
Auth Guard: Ensures that only authenticated requests proceed to the route handler.
Implementation:
Explanation:
Middleware: The
LoggerMiddleware
logs all incoming requests to any route (path: '*'
).Guard: The
AuthGuard
protects theusers
routes, ensuring that only authenticated requests can access them.
This setup ensures that every request is logged and only authenticated requests reach the route handlers.
Last updated