Introduction

One common use case in LWC development is interacting with external services to fetch data or perform actions.

What is the Fetch API?

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.

Using the Fetch API

Allowing external calls through CSP

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.

Untitled

<aside> 💡 Be aware that is some cases, this configuration takes some minutes to apply.

</aside>

Javascript

The following LWC, named FetchExample, it is an example on how to request an external API:

  1. In the connectedCallback lifecycle hook, we call the fetchDataFromExternalService function when the component is connected to the DOM.
  2. The fetchDataFromExternalService function makes a GET request to the specified URL using the Fetch API.
  3. The response object returned by the Fetch API is checked for its ok property. If it is not true, an error is thrown.
  4. The response data is parsed as JSON using the response.json() method and assigned to the responseData property of the component.
  5. Any errors that occur during the fetch process are caught and logged to the console.