79601779

Date: 2025-05-01 11:29:03
Score: 0.5
Natty:
Report link

For those who wondering about full example.

import { ExecutionContext, Injectable } from '@nestjs/common';
import { ThrottlerGuard } from '@nestjs/throttler';

function getIp(req): string {
  const forwarded = req.headers['x-forwarded-for'];
  if (typeof forwarded === 'string') {
    return forwarded.split(',')[0].trim();
  }
  return req.ips?.[0] || req.ip;
}

@Injectable()
export class ThrottlerBehindProxyGuard extends ThrottlerGuard {
  protected async getTracker(req: Record<string, any>): Promise<string> {
    return getIp(req);
  }

  protected getRequestResponse(context: ExecutionContext): {
    req: Record<string, any>;
    res: Record<string, any>;
  } {
    const httpContext = context.switchToHttp();
    return {
      req: httpContext.getRequest(),
      res: httpContext.getResponse(),
    };
  }
}

Then in your app.module providers array put this

providers: [
    {
      provide: APP_GUARD,
      useClass: ThrottlerBehindProxyGuard,
    },
  ],

After that, all @Throttle you will use, will follow rules of custom guard.

@Throttle({
    default: {
      limit: 1,
      ttl: 60 * 1000,
    },
  })
  @Post('forgot-password')
Reasons:
  • Long answer (-1):
  • Has code block (-0.5):
  • User mentioned (1): @Throttle
  • Low reputation (1):
Posted by: Artem