'how to I get a user's IP address when separate client and server apps, in Node with Nest.js
I have two apps, one front end (react.js) and one a REST API back-end(nest.js based on express.js). How do I get the IP address of the user accessing the back-end when the front-end client makes a request to the back-end?
I checked this question and try the solutions
With separate client and server apps, how do I get a user's IP address, in Node with Koa?
Express.js: how to get remote client address
but I get server IP of front-end not client IP.
Is there a way without any change in front-end app, I get real client IP in nest.js?
Solution 1:[1]
You may install a library called request-ip
:
npm i --save request-ip
npm i --save-dev @types/request-ip
In main.ts
file inject request-ip middleware within your app:
app.use(requestIp.mw());
Now you can access clientIp from request object:
req.clientIp
Another way is by defining a decorator:
import { createParamDecorator } from '@nestjs/common';
import * as requestIp from 'request-ip';
export const IpAddress = createParamDecorator((data, req) => {
if (req.clientIp) return req.clientIp;
return requestIp.getClientIp(req);
});
And you can use the decorator in controller:
@Get('/users')
async users(@IpAddress() ipAddress){
}
Check the following issue in github.
Solution 2:[2]
You can extract IP address from a Request
object.
I am using it as a middleware to print user's IP address in a log entry, here is how I do that:
import { Injectable, Logger, NestMiddleware } from "@nestjs/common";
import { NextFunction, Request, Response } from "express";
@Injectable()
export class HttpLoggerMiddleware implements NestMiddleware {
private logger = new Logger();
use(request: Request, response: Response, next: NextFunction): void {
const { ip, method, originalUrl } = request;
response.on("finish", () => {
const msg = `${ip} ${method} ${originalUrl}`;
this.logger.log(msg);
});
next();
}
}
Solution 3:[3]
If you are fine using 3rd-party library. You can check request-ip
Solution 4:[4]
According to the NestJS docs, there's a decorator available to get the request Ip Address. It's used like this:
import {Get, Ip} from "@nestjs/common"
@Get('myEndpoint')
async myEndpointFunc(@Ip() ip){
console.log(ip)
}
Here's a complete list of decorators that can be used: https://docs.nestjs.com/custom-decorators
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | rand0rn |
Solution 3 | Mike Gerard |
Solution 4 | Manuel Duarte |