2

Is there an elegant, non-hack way to get the user's IP address from within an LWC component? (Not an Aura component).

Thanks!

1 Answer 1

5

Assuming that you want to get the external public IP address and not the local one, the basic way would be to adapt the code from here

exampleIP.html

<template>
    {ip.data}
</template>

exampleIP.js

import { LightningElement, wire } from 'lwc';
import getExternalIp from '@salesforce/apex/LWC_Utils.getExternalIp';
export default class ExampleIP extends LightningElement {
    @wire(getExternalIp) ip;
}

LWC_Utils.cls

public class LWC_Utils {
      @AuraEnabled(cacheable=true)
      public static String getExternalIp() {
          return Auth.SessionManagement.getCurrentSession().get('SourceIp');
      } 
}

And by "basic" I mean that this example is "assuming all goes well", but you should actually control that there are no errors coming back from the class, and that it can be called (for example that it does not fail because the Profile does not have access to the class and the critical update that checks that is active)

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.