Nest: How to get client ip from the request?

Created on 22 Oct 2017  路  4Comments  路  Source: nestjs/nest

I want to get the client ip address, but I didn't find how to do it.

question 馃檶

Most helpful comment

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.

All 4 comments

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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

marshall007 picture marshall007  路  3Comments

cojack picture cojack  路  3Comments

KamGor picture KamGor  路  3Comments

artaommahe picture artaommahe  路  3Comments

yanshuf0 picture yanshuf0  路  3Comments