One common use case in LWC development is interacting with external services to fetch data or perform actions.
The Fetch API is a modern JavaScript API that provides an easy and efficient way to make network requests, including fetching resources from external URLs. It is a replacement for traditional methods like XMLHttpRequest
(XHR) and provides a more straightforward and flexible syntax for making HTTP requests.
Content Security Policy (CSP) in Salesforce is a security feature that helps prevent and mitigate potential risks from cross-site scripting (XSS) attacks and other code injection vulnerabilities.
It controls which sources of content can be loaded and executed within a Salesforce org, such as scripts, styles, and images.
By specifying trusted sources, CSP restricts unauthorized scripts from running, enhancing the overall security of Salesforce applications.
In order to allow our calls to the external service https://api.ipify.org which returns your IP, a configuration in your Salesforce instance is required as the folllows.
<aside> 💡 Be aware that is some cases, this configuration takes some minutes to apply.
</aside>
The following LWC, named FetchExample
, it is an example on how to request an external API:
connectedCallback
lifecycle hook, we call the fetchDataFromExternalService
function when the component is connected to the DOM.fetchDataFromExternalService
function makes a GET request to the specified URL using the Fetch API.response
object returned by the Fetch API is checked for its ok
property. If it is not true, an error is thrown.response.json()
method and assigned to the responseData
property of the component.