Strattic Developer Docs

How to Check the IP Address of a Visitor

Sometimes you need to check where someone’s IP address. However, you cannot do this directly in the browser, and traditionally you might have relied on a PHP server server to do this work.

Never fear, a serverless service is here! 🤓

This is a simple service that returns the X-Forwarded-For headers, which you can parse to get the person’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).

This is the serverless.yml file:

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

frameworkVersion: '2'

provider:
  name: aws
  runtime: nodejs12.x
  lambdaHashingVersion: '20201221'

functions:
  ipCheck:
    handler: handler.ipCheck
    events:
      - http:
          path: /
          method: get
          cors:
            headers: '*'

This is the handler.js file:

"use strict";

module.exports.ipCheck = async (event) => {
  const iPaddys = event.headers['X-Forwarded-For'].split(',');
  return {
    statusCode: 200,
    body: JSON.stringify(
      iPaddys[0],
      null,
      2
    ),
  };
};