Search code examples
typescriptnestjs

How to get IP address from request context nestjs?


I want to build simple authentication using IP addresses, some IP address that I whitelisted can access the API. But I got a problem when I use request.ip it only output ::1 which is not a real IP address.

How to get the user IP Address in nestjs? Here are my code right now


import {
  Injectable,
  CanActivate,
  ExecutionContext,
  Logger,
} from '@nestjs/common';
import { Observable } from 'rxjs';

@Injectable()
export class AuthGuard implements CanActivate {
  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    const request = context.switchToHttp().getRequest();
    const allowedIp: Array<string> = ['129.2.2.2', '129.2.2.2'];
    if (process.env.ENV === 'production') {
      const ip = request.connection.remoteAddress;
      Logger.log(ip, 'ACCESSED IP ADDRESS');
      if (allowedIp.includes(ip)) {
        return true;
      } else {
        return false;
      }
    } else {
      return true;
    }
  }
}

Edit:

Turns out that ::1 are valid address for 'localhost' but when I deploy it on server and access the app from browser its log ::ffff:127.0.0.1 not my real IP.


Solution

  • As I mentioned on Discord, you can use the header X-Forwarded-For as you're using nginx as a reverse proxy. The reason for getting ::1 is because that's the IP that the proxy is running on (i.e. localhost or 127.0.0.1)