0

Imagine we have code like this in the NestJS. No matter if it's Guard or Interceptor. In general the place that you have access to ExecutionContext.

import { CanActivate } from "@nestjs/common";

export class MyCustomGuard implements CanActivate {
  constructor() {}
  async canActivate(context: ExecutionContext): Promise<boolean> {
    const ctx = context.getType();
    if (ctx !== "rpc") return true;

    const rpc = context.switchToRpc();
    // ip validation
    return true;
  }
}

How can i get client ip address in grpc context?

1 Answer 1

0

After digging around I found this. we can discover the client IP address in ServerWritableStreamImpl instance at args[2]

import { CanActivate } from "@nestjs/common";

export class MyCustomGuard implements CanActivate {
  constructor() {}
  async canActivate(context: ExecutionContext): Promise<boolean> {
    const ctx = context.getType();
    if (ctx !== "rpc") return true;

     const rpc = context.switchToRpc();
     const [ip, port] = context.switchToRpc().args[2].call.getPeer().split(":");

    return true;
  }
}

Related useful link: how to get client IP address with node grpc

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.