How access request params in middleware in nest.js

How to Access Request Params in Middleware in Nest.js

When working with Nest.js, you may come across a scenario where you need to access request parameters in a middleware. Middleware functions in Nest.js are executed before the route handler and can be used for various purposes such as authentication, logging, error handling, etc. In this article, we will explore different ways to access request parameters in middleware in Nest.js.

1. Using the Request object

The simplest way to access request parameters in middleware is by using the request object. The request object contains all the information about the incoming request, including the request parameters. Here’s how you can access request parameters using the request object:

import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';

@Injectable()
export class CustomMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: NextFunction) {
    const param1 = req.params.param1;
    const param2 = req.params.param2;
    // Do something with the request parameters
    next();
  }
}

In the above example, we are accessing the request parameters param1 and param2 using req.params.param1 and req.params.param2. You can replace param1 and param2 with the actual parameter names you want to access.

2. Using the @Param() decorator

In Nest.js, you can also use the @Param() decorator to access request parameters in middleware. The @Param() decorator is a built-in decorator provided by Nest.js that allows you to extract parameters from the request object. Here’s how you can use the @Param() decorator:

import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
import { Param } from '@nestjs/common';

@Injectable()
export class CustomMiddleware implements NestMiddleware {
  use(@Param('param1') param1: string, @Param('param2') param2: string, req: Request, res: Response, next: NextFunction) {
    // Do something with the request parameters
    next();
  }
}

In the above example, we are using the @Param() decorator to extract the request parameters param1 and param2. The decorator takes the parameter name as an argument and assigns the corresponding value to the decorated parameter.

Conclusion

In this article, we explored different ways to access request parameters in middleware in Nest.js. You can use the request object or the @Param() decorator to access request parameters in middleware. Choose the method that best suits your requirements and implement it in your Nest.js application.

That’s it for this article! Happy coding!


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *