Strattic Developers by Elementor

Use an IP Address to Get Location Info with ipstack

While you might already know how to check for an IP address, you might also want to gather a little more information about a user’s location based on their IP address. ipstack (yes, all lowercased) is one of the best services for this, and you can get started for free.

Check these details, signup, and go to the Quickstart guide to get up and running with your API key.

First we check the X-Forwarded-For headers to get the user’s IP address.

Normally, it is the first header in the list that is the IP (you can check this with a VPN as well).

Then we send that information along with our API key to ipstack.com and get back a response of information. You can parse the information and select what you’d like to send back to the browser in your service.

This type of service is useful if you’d like to show different content based on a user’s IP address or country location.

This is the package.json file:

{
  "name": "ipstack-demo",
  "version": "1.0.0",
  "description": "Check IPs for more info.",
  "main": "handler.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "node-fetch": "^2.6.7"
  }
}

You’ll want to run npm-install to make sure the node modules you need are available. You’ll want to do two additional steps:

Run npm install node-fetch --save-dev to install the node-fetch module.

This is the serverless.yml file:

org: your-org
app: byol-ip-checker
service: byol-ip-checker

frameworkVersion: '3'

provider:
  name: aws
  runtime: nodejs14.x
  environment:
    IPSTACK_API_KEY: ${param:ipStackAPIKey}

package:
  patterns:
    - '!node_modules/**'
    - 'node_modules/node-fetch/**'
    - 'node_modules/whatwg-url/**'
    - 'node_modules/webidl-conversions/**'
    - 'node_modules/tr46/**'

functions:
  ipLocation:
    handler: handler.ipLocation
    events:
      - httpApi:
          path: /
          method: get

This is the handler.js file:

"use strict";
const fetch = require('node-fetch');

exports.ipLocation = async (event) => {
  const apiKey = process.env.IPSTACK_API_KEY;
  const iPaddys = event.headers['x-forwarded-for'].split(',');

  // Take the first IP address and send it to ipstack with the API key.
  const response = await fetch(`http://api.ipstack.com/${iPaddys[0]}?access_key=${apiKey}`);
  const data = await response.json();

  return {
    statusCode: 200,
    body: JSON.stringify(
      {
        message: "We got some IP data back.",
        ipInfo: data,
      },
      null,
      2
    ),
  };
};