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?
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.