How do Lightning Web Components integrate with external APIs using native fetch and Apex controllers?
Answer
Basics: LWC runs in the browser, so it can use fetch(), but Salesforce's Content Security Policy only allows connections to approved origins. Apex runs on the server, can store credentials safely, and is not subject to CORS.
How it works:
- Apex route (preferred):
@AuraEnabledmethod does theHttpcallout usingcallout:Named_Credential, returns data; the LWC calls it imperatively or via@wirefor cacheable reads. - Direct fetch route: add the external origin under Setup > CSP Trusted Sites (directive
connect-src), and the external server must return proper CORS headers allowing your Salesforce origin. Suitable only for public, non-secret APIs. - Long-running callouts can use
Continuation(up to 3 callouts per continuation, timeout up to 120 seconds).
Advanced / deep dive: Named Credentials keep secrets and OAuth flows out of code and support per-user or named-principal identity (External Credentials in current versions). @AuraEnabled(cacheable=true) methods can perform callouts but cannot do DML; cached responses may be stale, so use refreshApex. Limits still apply: 100 callouts per transaction, 120 s cumulative timeout, 6 MB sync heap. A callout cannot occur after uncommitted DML in the same transaction. LWS/Locker restrict some browser APIs. For read-heavy third-party data, consider caching in Platform Cache or storing in custom objects, or use External Objects (OData/Salesforce Connect) to avoid custom code.
Code / config example:
public with sharing {
String {
();
req.setEndpoint( + EncodingUtil.urlEncode(city, ));
req.setMethod();
req.setTimeout();
().send(req);
(res.getStatusCode() != ) ( + res.getStatusCode());
res.getBody();
}
}