Apex – Making a Callout from LWC or Apex

apexcalloutlightning-web-components

Most examples of implementing a callout as part of a LWC involve calling an Apex method that handles the callout and returns the response to the JS controller. What are the reasons we callout from Apex, rather than handling the HTTP request client-side?

I'm thinking of a couple reasons but would like to check my understanding.

  1. Calling from client side would expose the headers in the network request from the Network browser inspection tab.
  2. If we pull our credentials from a metadata record in Salesforce setup, we then expose these directly in the client. (But isn't the file minified and obscured in a production environment?)

Am I understanding these correctly? And what are some other reasons?

Best Answer

We use Apex to reduce the possibility of security risks, as clients are relatively insecure. Using Apex can reduce the data exposed to the client, and avoid leaking secrets, such as private keys, passwords, or other kinds of API keys.

The CSP (Content Security Policy) of Lightning prohibits CORS (Cross-Origin Resource Sharing) in order to improve security, as well as mitigating the possibility of Cross Site Scripting (XSS) attacks. This limits the kinds of resources that can be loaded, which reduces possible attack vectors.

Further, the remote site needs to set Access-Control-Allow-Origin, otherwise the browser will reject the connection after performing a preflight callout. Therefore, CORS may not be applicable to various services, since many services do not allow this kind of scripting, also as a security feature.

Related Topic