NestJS How to get client IP from the request with code examples
This tutorial explains how to get Client IP address from a request in NestJS
. One way is using the @ip
decorator provided by Nestjs, the Second way using the express request ip
property, Third-way using nests real ip decorator third-party npm library.
NestJS how to get the Client IP Address from a Request using IP decorator?
NestJS provides parameters decorator @Ip
with HTTP routes. @Ip decorator is equivalent to request.ip in the Express framework
import { Controller, Get, Ip } from "@nestjs/common";
@Controller("api")
export class AppController {
constructor() {}
@Get("/ip")
getIpAddress(@Ip() ip) {
console.log(ip);
return ip;
}
}
Get IP address using express request object in Nestjs
In this example, an express Request contains IP property that returns IP address.
- Import Request into the controller
import { Request } from 'express';
- @Get decorator added to the method, that accepts the
@Req
object of type Request in the express. - get Ip address using request.ip property
Here is an example
import { Controller, Get, Req } from "@nestjs/common";
import { Request } from "express";
@Controller("api")
export class AppController {
@Get()
getIpAddress(@Req() request: Request): string {
const ipAddress = request.ip;
return ipAddress;
}
}
nestjs-real-ip npm library to Get Remote IP address
nestjs-real-ip🔗 is a third-party library that provides nestjs decorator to get IP address as a string, can be used in controller classes
Install npm using the below command in the terminal
npm install nestjs-real-ip
RealIP is a decorator used in the controller, import RealIP into the controller.
import { RealIP } from "nestjs-real-ip";
Here is an example
import { Controller, Get } from "@nestjs/common";
import { RealIP } from "nestjs-real-ip";
@Controller("api")
export class AppController {
@Get("ip")
getIpAddress(@RealIP() ip: string): string {
return ip;
}
}
How do I find the client IP address in Nest JS?
To get Client Ip address in Nestjs, Please follow below steps
- Nestjs provides @Ip decorator to get IP address
- pass this @Ip decorator to method of an controller
- Object of this parameter holds the real ip address