Retrieve the IP Address using Express and GraphQL

Seeking assistance here! I recently made the switch from using rest to gql, but encountered an issue along the way. In my previous setup with rest, I was able to retrieve the user's IP address using req.ip. However, when trying to implement this in the resolve() function of GraphQL, the value returned was undefined. After some research, I came across the following solution:

const server = new GraphQLServer({
  context: context => ({
    ...context,
    db,
    userIp: maybeGetUserIpAddress(context.request),
  }),
});

const maybeGetuserIpAddress = (request): ?string => {
  const headers = request.headers;
  if (!headers) return null;
  const ipAddress = headers['x-forwarded-for'];
  if (!ipAddress) return null;
  return ipAddress;
};

Unfortunately, this also resulted in returning undefined.

Therefore, I have a couple of questions:

1. Could this issue be related to hosting my server locally?
2. What might be incorrect in the provided code snippet?

Answer №1

A common misconception is that using req.ip and req.socket.remoteAddress on localhost will work.

However, there is a better alternative:

(req -> express.Request)

  const ip = require('ipware')().get_ip(req)?.clientIp || req?.ip || req?.socket?.remoteAddress || '127.0.0.1'

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

When the functions Serialize and Deserialize are invoked within the context of passport.js

I am curious about the timing of when Serialize and Deserialize functions are called. I tried testing it by adding alert(user.id) but nothing happened. Here are some questions I have: Where does the user object come from in the passport.serializeUser(fu ...

When attempting to host a React application within an Express server, an error is encountered with the message "

I am looking to host my react app, created with create-react-app, using an express app. This is the express app I have written: const express = require('express') const path = require('path') const app = express() console.log(path.re ...

Searching for particular information within an array of objects

Seeking guidance as a newbie on how to extract a specific object from an array. Here is an example of the Array I am dealing with: data { "orderid": 5, "orderdate": "testurl.com", "username": "chris", "email": "", "userinfo": [ ...

Make sure to call super.onDestroy() in the child component before overriding it

I find myself with a collection of components that share similar lifecycle logic, so I decided to create a base component that implements the OnDestroy interface. abstract class BaseComponent implements OnDestroy { subscriptions = new Array<Subscript ...

Submitting the form leads to an empty dynamically added row

I am currently working on a gender overview that allows you to edit, add, or delete genders using a simple table. The functionality of adding and deleting rows is already implemented. However, I am facing issues with displaying the correct web API data as ...

issue with making simultaneous async requests in PERN stack application

In the process of developing an inventory management application using PERN stack, I encountered a challenge with a modal where I need to make 2 GET requests. While both requests return a Status 200 response when logged in the front end, the issue arises w ...

Vue's span function is yielding the promise object

In my Vue component, I am using the function getOrderCount to fetch the number of orders from a specific URL and display it in one of the table columns. <div v-html="getOrderCount(user.orders_url)"></div> async getOrderCount(link) { ...

"Encountering an error with the any type in the useLocation feature while using React Router version 6

https://i.sstatic.net/0YcS9.png What steps should I take to resolve this particular type of error issue? My attempt at passing a custom type did not yield successful results. ...

Alerts in Angular templates of inherited class in WebStorm

While working with WebStorm 2019.3.2, I have noticed some warnings in Angular templates: https://example.com/image.png This is happening because the properties are being initialized on the parent component instead of the child. @Component({ selector: ...

Update the image on a webpage by simply clicking on the current image

Hey there, I'm looking to implement a feature where users can choose an image by clicking on the current image itself. Here's my code snippet. The variable url holds the default image. My goal is to make the current image clickable so that when ...

How can I use Typescript to define a function that accepts a particular string as an argument and returns another specific string?

I've been working on this code snippet: const Locales = { en_gb: 'en-gb', en_us: 'en-us', } as const type ApiLocales = typeof Locales[keyof typeof Locales] type DatabaseLocales = keyof typeof Locales function databaseLanguage ...

Visualizing the web page with API response

I successfully retrieved the API call response in JSON format through console.log() in my Node console. Now, I am looking for a way to display this result on my webpage with some styling. Within my app.post() function, I have included the console.log() st ...

What is the best way to attach an event listener to a session (redis) using nodejs and express?

How can I trigger a function in nodejs with express using a redis session store whenever a user's session is destroyed or times out? ...

What is the best location to store custom Handlebars helpers within an Express application?

Currently, I am delving into the realm of Node.js and diving into an application with Express + Handlebars. I have reached a part where I must create my own helper for the Handelbars view engine. After defining my helper using the registerHelper() method ...

Looking for a youtube.d.ts file to integrate the youtube-iframe-api with Angular 2?

My current challenge involves implementing the youtube iframe api for seamless video snippet display and control within an Angular 2 application. Maintaining TypeScript's type concept is crucial for both the webpack compiler and myself :). A brief ov ...

The revalidation process in react-hook-form doesn't seem to initiate

Stumbled upon a code example here Decided to fork a sandbox version (original had bugs and errors) I am trying to implement custom validation callbacks for each form input element by providing options in the register function, but the validate is only tr ...

I'm encountering difficulty accessing the Index value within the template's Ref

I'm having trouble accessing the index value inside the templateRef. It shows as undefined in the console. <ng-container *ngFor="let notification of notifications; let i = index"> <ng-template *ngTemplateOutlet="notificationPage ...

What steps are involved in developing a content management system similar to WordPress that can be easily set up within an

My apologies for any language barriers. I am interested in learning how to develop a content management system (CMS) similar to WordPress, which users can install on their own hosting. Basically, I want to create a user-friendly CMS that can be distribut ...

Error code 2532 occurs when trying to access an object using square brackets in TypeScript

Encountered the ts error: Object is possibly 'undefined'.(2532) issue while trying to access the value of a field within an object, where the object key corresponds to a value in an Enum. Below is a concise example to showcase this problem: en ...

Require fields in TypeScript interfaces only for array types

Is there a way to make only array type interface fields required, not all of them? The Required operator currently makes every field mandatory, but I specifically need just the array fields to be required. ` interface IExample { a: number, b?: str ...