How to Detect User IP Address in Salesforce Using Flow, Apex, and LWC

April 17, 2026
79 Views
How to Detect User IP Address in Salesforce Using Flow, Apex, and LWC
Summarize this blog post with:

In public-facing Salesforce applications such as Experience Cloud portals, Salesforce Sites, and Screen Flows, capturing the user’s IP address plays an important role in security and tracking.

IP Detection helps identify the user’s location and ensures better monitoring of incoming requests. It can also be used as an additional layer of validation before allowing users to proceed further in the system.

Why IP Detection is Important

Without IP tracking, systems are vulnerable to:

  • Anonymous access without traceability
  • Fraudulent or suspicious activities
  • Geo-restricted service misuse
  • Lack of audit and monitoring capability

A simple IP Detection mechanism helps in identifying the user’s origin and strengthens overall system security.

What is IP Detection?

IP Detection is a process of capturing and analyzing the user’s public IP address.

In this implementation:

  • LWC fetches the user’s public IP
  • Flow passes the IP to Apex
  • Apex calls an external API to fetch location details
  • Country and City are returned back to the Flow

Architecture Overview

User → Flow Screen (LWC) → Fetch IP → Send to Flow → Apex Action → External API Call → Return Location → Display in Flow

How It Works in Salesforce

Step 1: Capture IP in LWC

The LWC component calls an external API:

https://api.ipify.org?format=json

LWC HTML Code:

<template>
    <lightning-card title="IP Detection">
        <p>Fetching IP...</p>
    </lightning-card>
</template>
LWC JS Code:

import { LightningElement, api, track } from 'lwc';
import { FlowAttributeChangeEvent } from 'lightning/flowSupport';
export default class ipCapture extends LightningElement {
    @api ipAddress;
    @track isLoaded = false;
    connectedCallback() {
        this.fetchIP();
    }
    fetchIP() {
        fetch('https://api.ipify.org?format=json')
            .then(response => response.json())
            .then(data => {
                console.log('IP fetched:', data.ip);
                this.ipAddress = data.ip;
                // send value to flow
                this.dispatchEvent(
                    new FlowAttributeChangeEvent('ipAddress', this.ipAddress)
                );
                this.isLoaded = true; // enable UI
            })
            .catch(error => {
                console.error('Fetch failed:', error);
                this.ipAddress = 'NOT_AVAILABLE';
                this.dispatchEvent(
                    new FlowAttributeChangeEvent('ipAddress', this.ipAddress)
                );
                this.isLoaded = true;
            });
    }
    @api
    validate() {
        if (!this.isLoaded || !this.ipAddress) {
            return {
                isValid: false,
                errorMessage: 'Please wait, fetching IP address...'
 
            };
        }
        return { isValid: true };
    }
}
LWC XML Code:(Important for Flow)
<isExposed>true</isExposed>
    <targets>
        <target>lightning__FlowScreen</target>
    </targets>
    <targetConfigs>
        <targetConfig targets="lightning__FlowScreen">
            <property name="ipAddress" type="String" role="outputOnly"/>
        </targetConfig>
    </targetConfigs>
Step 2: Send IP to Flow
The fetched IP is stored in a Flow variable (ipAddress).

IP Detection in Salesforce Flow Apex LWC 1

Step 3: Call Apex from Flow
IPDetectionService.getIPDetails

IP Detection in Salesforce Flow Apex LWC 2

Step 4: Call External API in Apex
https://ipapi.co/{IP}/json/
Apex Code:
public with sharing class IPDetectionService {
public class IPResult {
@InvocableVariable(label='IP')
public String ip;
@InvocableVariable(label='Country')
public String country;
@InvocableVariable(label='City')
public String city;
}
@InvocableMethod(label='Get IP Details')
public static List<IPResult> getIPDetails(List<String> input) {
List<IPResult> results = new List<IPResult>();
// STEP 1: Get IP from Flow (LWC)
String ip = (input != null && !input.isEmpty()) ? input[0] : null;
// If no IP received
if (String.isBlank(ip)) {
IPResult r = new IPResult();
r.ip = 'NOT_AVAILABLE';
r.country = 'UNKNOWN';
r.city = 'UNKNOWN';
results.add(r);
return results;
}
try {
// STEP 2: Call ipapi
HttpRequest req = new HttpRequest();
req.setEndpoint('https://ipapi.co/' + ip + '/json/');
req.setMethod('GET');
req.setTimeout(5000);
Http http = new Http();
HttpResponse res = http.send(req);
if (res.getStatusCode() == 200) {
Map<String, Object> data =
(Map<String, Object>) JSON.deserializeUntyped(res.getBody());
// STEP 3: Map response
IPResult r = new IPResult();
r.ip = ip;
r.country = (String) data.get('country_name');
r.city = (String) data.get('city');
results.add(r);
} else {
IPResult r = new IPResult();
r.ip = ip;
r.country = 'API_ERROR';
r.city = 'API_ERROR';
results.add(r);
}
} catch (Exception e) {
IPResult r = new IPResult();
r.ip = ip;
r.country = 'ERROR';
r.city = 'ERROR';
results.add(r);
}
return results;
}
}
Step 5: Parse and Return Response
IP, Country, City are returned.

IP Detection in Salesforce Flow Apex LWC 3

Step 6: Display Data in Flow
Flow displays IP, Country, City.

IP Detection in Salesforce Flow Apex LWC 4

Error Handling

  • NOT_AVAILABLE (No IP)
  • API_ERROR (API failure)
  • ERROR (Exception)

Key Features

  • Real-time IP capture
  • Flow + LWC + Apex integration
  • External API-based detection
  • Validation before navigation
  • Error handling

Security Benefits

  • User tracking
  • Fraud detection
  • Geo restrictions
  • Audit support

Use Cases

  • Experience Cloud
  • Salesforce Sites
  • Public Forms
  • Login/Registration Flows

Important Configurations:

To ensure that IP Detection works correctly in Salesforce, certain configurations must be completed.
1. Trusted URLs (CSP Settings)

Since the LWC component calls an external API, the endpoint must be added to Trusted URLs.

Add the following URL:

https://api.ipify.org

IP Detection in Salesforce Flow Apex LWC 5

This allows the browser to make external API calls from LWC without being blocked by CSP (Content Security Policy).

2. Remote Site Settings (Apex Callout)

Apex callouts require Remote Site Settings configuration.

Add the following:

Name: ipapi

URL: https://ipapi.co
IP Detection in Salesforce Flow Apex LWC 6

Without this, the Apex HTTP callout will fail.

Real-Time Use Case: IP Detection from Record Page

In this implementation, IP Detection is triggered directly from an Account record using a button, making the solution more interactive and user-driven.

How It Works?

Step 1: Add Button on Account Record

IP Detection in Salesforce Flow Apex LWC 7

A custom button is created on the Account object. When the user clicks the button, it launches the Screen Flow.

Step 2: First Screen (LWC – IP Capture)

The first screen contains the LWC component.

  • IP address is fetched automatically
  • User is not required to enter any input

IP Detection in Salesforce Flow Apex LWC 8

This ensures accurate and real-time IP detection
Step 3: Click on NEXT

Once the IP is successfully fetched, the user clicks NEXT.

The IP is passed to the Flow and sent to Apex for processing.

Step 4: Second Screen (Display Details)

The second screen displays the IP details:

  • IP Address
  • Country
  • City

IP Detection in Salesforce Flow Apex LWC 9

This provides a clear view of the user’s location information.

Architecture Flow

Account Record → Button Click → Screen Flow → LWC (Fetch IP) → NEXT → Apex Call → Show IP Details

Benefits of This Approach

  • Easy to trigger from record level
  • No manual input required
  • Real-time data capture
  • Improved user experience
  • Better visibility for admins

Conclusion

IP Detection provides a simple yet powerful way to enhance security and visibility in Salesforce applications.

With depth LWC, Flow, Apex you can get and analyze a user’s IP address in real-time, which allows us to augment the validation process and monitoring by knowing the user location.

This method not only allows for monitoring the user activity but also provides an extra security layer for applications exposed to the public.

VPN Uses

IP Detection in Salesforce Flow Apex LWC 10                        IP Detection in Salesforce Flow Apex LWC 11

How useful was this post?

Click on a star to rate it!

Average rating 5 / 5. Vote count: 2

No votes so far! Be the first to rate this post.

Written by

Rohit Mehta

A passionate Salesforce Developer and 3x Salesforce Certified professional specializing in building scalable CRM solutions. Proficient in Apex, Lightning Web Components (LWC), Triggers, Flows, and integrations, with a strong focus on delivering efficient, user-friendly applications. Experienced in translating business requirements into robust technical solutions while optimizing system performance. Skilled in end-to-end development, from design and implementation to deployment across Salesforce platforms.

Get the latest tips, news, updates, advice, inspiration, and more….

Contributor of the month
contributor
Mykyta Lovygin

SFCC Developer | SFCC Technical Architect | Salesforce Consultant | Salesforce Developer | Salesforce Architect |

...
Categories
...
Boost Your Brand's Visibility

Want to promote your products/services in front of more customers?

...

Leave a Reply

Your email address will not be published. Required fields are marked *