What is the best way to extract the IP address from the request context in NestJS?

I'm looking to implement a basic authentication system using IP addresses, where only whitelisted IPs can access the API. However, I've encountered an issue with obtaining the user's actual IP address when using request.ip, as it only returns ::1 which is not a valid IP.

How can I retrieve the user's IP Address in nestjs? Below is my current code:


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:

It appears that ::1 is a valid address for 'localhost'. However, when deployed on a server and accessed from a browser, it logs ::ffff:127.0.0.1 instead of the real IP address.

Answer №1

In our previous discussion on Discord, I suggested utilizing the X-Forwarded-For header when utilizing nginx as a reverse proxy. The reason you are seeing ::1 is because that is the IP address that the proxy server is operating on (i.e. localhost or 127.0.0.1)

Answer №2

const findTokenByUserData = async (@Context() context, @Args('token') token: string) => {
    const {
      req: { user, ip },
    } = context;
    console.log({ ip });
    const { userId } = user || {};
    // Your code here

You can retrieve the IP address and see ::1 for localhost

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Volta alert: Temporary directory creation failed

Recently, I attempted to globally download and install TypeScript using the npm install -g typescript command in my terminal. Unfortunately, an error occurred: Volta error: Could not create temporary directory in /Users/username/.volta/tmp/image/packages ...

Assign a property to an array of objects depending on the presence of a value in a separate array

Looking to manipulate arrays? Here's a task for you: const arrayToCheck = ['a', 'b', 'c', 'd']; We have the main array as follows: const mainArray = [ {name:'alex', code: 'c'}, ...

Challenge with React CloneElement regarding typing

Utilizing React Children and React Clone element, I aim to trigger methods in both the wrapper and Select components upon onClick event in the Option component. Although everything is functioning correctly, I am encountering a type error when calling the O ...

Connecting Angular modules via npm link is a great way to share common

Creating a project with a shared module that contains generic elements and components, such as a header, is my goal. This shared module will eventually be added as a dependency in package.json and installed through Nexus. However, during the development ph ...

Generate a random string and return it as a value

I am looking to incorporate JavaScript code into my Angular application. I attempted the following approach: export class MerchantNewComponent extends FormBaseComponent { constructor(private merchantService: MerchantService, private route ...

Issues arise when attempting to use recursive types in combination with optional properties

In my code, I've created a type definition that allows me to traverse an object using an array of strings or indices representing the keys of the object or nested arrays: export type PredicateFunction<ArrayType> = (array: ArrayType, index?: numb ...

Error in Angular compiler-cli: The namespace 'ts' does not contain the exported member 'ResolutionMode'

Currently working on a web application using Angular 16 in Webstorm. The application is still in the pre-release stage, with only minimal functionality completed so far. While editing with ng serve running to test changes as they were made, encountered an ...

Toggle the visibility of a modal in code across various components in an Angular 4 project using Typescript

As I was working on my university App, I encountered an issue while attempting to open a Bootstrap modal in code from a different component. Opening a component in code from the same component posed no problems for me as I use JQuery and it functions perfe ...

Manipulating Angular and Typescript to utilize the method's parameter value as a JavaScript object's value

I am currently working with Ionic, Angular, and Typescript, attempting to dynamically set the value of a location based on the parameter passed from a method. Here is the relevant code snippet: async fileWrite(location) { try { const result = a ...

Access the RxJS subscription data once and save it for later reuse

Currently, I am retrieving plans from a service using RxJS: public class PlansListComponent implements OnInit { private plans$: Subject<PlanDTO> = new BehaviorSubject([]); ngOnInit():void { this.serverService .list() .subscribe( ...

Adjust website content depending on user's authentication status

My goal is to display a logout button when the user is logged in and a login button if they are not. I am using JSON tokens to determine if a user is logged in or not, by checking if the token is null. However, this approach does not seem to be working. Ca ...

Is there a solution for resolving the 'cannot post error' in nodejs?

Recently started using node.js I am currently working on a nodejs-experss-mongodb project and I am in the process of implementing a subscription feature that has the following specific requirements: Request Method: POST URL: localhost:8080/api/v1/users/: ...

My component is displaying a warning message that advises to provide a unique "key" prop for each child in a list during rendering

I need help resolving a warning in my react app: Warning: Each child in a list should have a unique "key" prop. Check the render method of `SettingRadioButtonGroup`. See https://reactjs.org/link/warning-keys for more information. at div ...

Webpack can generate separate compiled files in addition to the bundle

Currently, I am utilizing the webpack loader ts-loader to convert typescript source files into a javascript bundle. My goal now is to not only save the compiled javascript bundle but also the individual compiled javascript files. While I have experience ...

Identify the general type according to a boolean property for a React element

Currently, I am facing a scenario where I need to handle two different cases using the same component depending on a boolean value. The technologies I am working with include React, Typescript, and Formik. In one case, I have a simple select box where th ...

Incorrect types being identified

What is the reason behind the callback assuming the type string | number | boolean instead of determining the exact type based on the property passed as the first argument in the carWithListener.on function? const car = { paint: "red", ...

Unable to organize list of entities based on numerical values

I am working with an array of objects structured like this: [ { "value": 351.68474, "o_p": [ "$.text" ] }, { "value": 348.0095, "o_p": [ ...

Is there a way to dynamically shift arrow key focus onto buttons in Angular using the left and right arrow keys?

I am facing an issue where pressing the arrow keys left and right does not focus or allow me to navigate through these buttons using the arrow keys. However, when checking the keycode values, they are printed according to the key pressed. I would like to k ...

Preventing the automatic selection of the initial item in a PrimeNG dropdown menu

While utilizing the p-menu component from PrimeNG in popup mode ([popup]="true"), I encountered an unexpected issue where the first item in the menu is automatically selected and turns gray. Here is the code snippet that I am using: <p-menu #menu [popu ...

What is the best way to organize objects based on their timestamps?

I am faced with the task of merging two arrays of objects into a single array based on their timestamps. One array contains exact second timestamps, while the other consists of hourly ranges. My goal is to incorporate the 'humidity' values from t ...