Cacheable Apex controllers for custom storefront components
Key Takeaway
@AuraEnabled(cacheable=true) caches an Apex response in the browser. Adding scope='global' also makes it cacheable on the Salesforce CDN, so use that option only for public data.
A cacheable Apex controller is an Apex method, marked with a caching annotation, that a custom storefront Lightning web component calls to get data. Caching stores the response so repeat requests can skip the server, which makes pages load faster. In a Commerce storefront, custom Apex is the last choice for getting data, so check the other options first.
When to use custom Apex
Custom storefront components can get data three ways, listed here in order of preference.
- Data providers
- The client-side storefront APIs
- Custom Apex controllers
Use Apex only when the first two aren't available or sufficient, because they already avoid unnecessary server requests and keep data consistent on the page.
Data providers are built on top of the client-side storefront APIs and share their optimizations. They are essential for getting server-side data during server-side rendering (SSR).
Custom fields alone are not a reason to write Apex. The client-side storefront APIs support custom fields, so a custom field added to Product2 is included in the product payload.
Don't call Connect APIs directly with fetch() or XmlHttpRequest. Use the client-side storefront APIs instead.