How to detect and pass incoming user ip information in react js applicaion ?

Let us see how we can detect and pass the user ip information when developing a react js application. For this guide I will be using Next JS framework.

General Information

Detecting the users IP information in react js application or in any kind of application is useful for many reasons and can be utilized in scenarios like IP specific authentication, specific information for users coming from different locations,etc.

How can we get the IP ?

Getting a user ip details specifically in javascript would be not possible, this can be achieved in server side and you will be able to detect and get the information from the incoming request coming in your server from the headers of the request.

Setup

Let us setup the project first, we will be using the framework called as Next Js - A React Framework, which I consider as a great framework to get started quickly in react and it has a lot of predefined features which you can directly use. Some of the features like Server side Rendering, SEO friendly, static websites, etc.

You can quickly set up the next js project as below :

  • Open up your terminal and run the below command :

    • npx create-next-app <project_name> (Keep in mind to create your project directory and CD inside it)

      Note:

      • npx command will work with npm 5.2 + or higher.
      • If using an older version of npx, consider setting up with manual option here
  • The above command will create a starter project for you in nextjs with complete structure of files and folder. It will automatically install react, react-dom and next npm modules for you with an example page and layout components.
  • This complete project already includes the below :

    • Automatic transpilation and building (with webpack and babel)
    • Hot code reloading
    • Server rendering and indexing of ./pages/

I will not go into much detail about each and every file and basic structure of the above(this may be covered in a separate post).

Cusomize the code

Now in your project folder create a custom server file with name server.js and place it inside the main directory and update the package.json scripts like shown below.

server.js
    const express = require('express')
    const next = require('next')

    const port = parseInt(process.env.PORT, 10) || 3000
    const dev = process.env.NODE_ENV !== 'production'
    const app = next({ dev })
    const handle = app.getRequestHandler()

    app.prepare().then(() => {
    const server = express()

    server.all('*', (req, res) => {
        return handle(req, res)
    })

    server.listen(port, err => {
        if (err) throw err
        console.log(`> Ready on http://localhost:${port}`)
    })
    })

install express js -> npm i express --save

package.json
"scripts": {
    "dev": "node server.js",
    "build": "next build",
    "start": "cross-env NODE_ENV=production node server.js"
  }

Try running the project with command npm run dev , and browse to your localhost:3000 to see the working react js applicaiton built using nextjs framework.

As we are done with the project setup and are ready with working codebase, lets add functionality to detect the incoming users IP request in express js server, that we created above with custom file.

Detect the IP

To detect the IP information of the incoming requests coming to your server we will be using the request-IP plugin, a node js plugin which gets the IP information from the requests.

The request-IP plugin searches for the below headers in the Incoming Requests and if not found then it falls back to NULL value:

  • X-Client-IP
  • X-Forwarded-For
  • CF-Connecting-IP (Cloudflare)
  • Fastly-Client-Ip (Fastly CDN and Firebase hosting header when forwared to a cloud function)
  • True-Client-Ip (Akamai and Cloudflare)
  • X-Real-IP (Nginx proxy/FastCGI)
  • X-Cluster-Client-IP (Rackspace LB, Riverbed Stingray)
  • X-Forwarded, Forwarded-For and Forwarded (Variations of #2)
  • req.connection.remoteAddress
  • req.socket.remoteAddress
  • req.connection.socket.remoteAddress
  • req.info.remoteAddress

Now let us modify the server file to the detect IP

  • Create a route named user-ip as shown below

            app.prepare().then(() => {
            const server = express()
    
            server.get('/user-ip', (req, res) => {
                ip = requestIp.getClientIp(req)
                app.render(
                    {
                    ...req,
                    clientIP : ip
                    },
                    res,
                    '/userIP',
                    req.query
                )
            })
    
            server.all('*', (req, res) => {
                return handle(req, res)
            })
  • Import and use the request-ip plugin in server.js like below

            const requestIp = require('request-ip')  // import it at the top 
    
            ip = requestIp.getClientIp(req)  // inside the route 

Don't forget to install the module -> npm i request-ip --save

Now the IP will be available in the clientIP variable please note it can be IPv4 or IPv6 IP address and can also be NUll if not found, so validate accordingly (but generally IP address if found).

Next, we need to send this IP address to the react page, please see the below this is an req. object being send to the next js page - see above user-ip route if you are in doubt.

{
    {
      ...req,
      clientIP : ip
    },
    res,
    '/userIP',  // userIP name should match with the page file name present in pages folder.(`userIP.js`)
    req.query
}

Note: The userIP page should already exist in the pages folder of your project.(Create one like below)

    import React from 'react'

    const userIP = (props) =>{
        return(
                 <div>
                   Incoming user IP is {props.clientIP}
                </div>
                )
            }

        userIP.getInitialProps = async (context) => {
            const isServer = !!context.req
                 return {
                  isServer,
                  clientIP: context.req ? context.req.clientIP : null
                  }
          }

        export default userIP

The IP will be receivced as props in the component and is being used and showed inside the div.

Another way of using Request-IP

The Request-IP plugin can also be used as a middleware and can detect and attach the IP in the incoming request(req)parameter, add the following if you want to use in this manner:

    const requestIp = require('request-ip');
    app.use(requestIp.mw())
        
    app.use(function(req, res) {
    const ip = req.clientIp;
    res.end(ip);
    });

Conclusion

With a node js plugin request-ip we were able to detect and pass the ip information from a custom express js server. Thanks for giving your time and reading it, if any mistakes are found please do inform me(through email) so that we can mantain a well structured and documented content.