I want to get the client ip address, but I didn't find how to do it.
Not sure exactly where you want retrive this address, but on controller level you have access to req
object, through @Request()
decorator. You can look for ip either at req.ip
, req.connection.remoteAddress
or in the headers eg. x-forwarded-for
in case your app is behind some proxy.
Hi @ufosky,
The @Rafal2228 solution should work for you. Btw you can use @Req()
decorator as well
If somebody stumbles on this, here is working solution using request-ip library.
Install library:
npm install --save request-ip
npm install --save-dev @types/request-ip
Optionally add to main.ts
:
app.use(requestIp.mw());
Then define new 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); // In case we forgot to include requestIp.mw() in main.ts
});
Now you can use it in controller with @IpAddress() ipAddress
.
This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
Most helpful comment
If somebody stumbles on this, here is working solution using request-ip library.
Install library:
Optionally add to
main.ts
:Then define new decorator:
Now you can use it in controller with
@IpAddress() ipAddress
.