Sub topic 1
Exposing an Apex method with @AuraEnabled
This chapter covers how to make an Apex method callable from a Lightning Web Component (LWC). Later chapters cover importing the method and calling it from JavaScript.
Prerequisites
This chapter assumes you know the following:
- Basic Apex syntax and SOQL.
- LWC fundamentals: templates, decorators, and event handlers.
- Basic JavaScript, including modules, objects, and Promises.
- How to deploy code to a Salesforce org or scratch org.
What @AuraEnabled does
Apex runs on the server. An LWC runs in the browser. The @AuraEnabled annotation marks an Apex method as reachable from client-side code. Without it, the LWC import fails at deploy time because the platform does not see the method as callable.
The annotation is shared by Aura components and LWC, which is why the name mentions Aura.
Rules for an exposed method
A method must meet these requirements:
- It is
static. - It is
publicorglobal. - It lives in a top-level Apex class.
- Its parameters and return type are types that can be serialized to JSON, such as primitives,
Id, sObjects, collections, and Apex classes with@AuraEnabledproperties.
Overloaded methods are not supported. Give each exposed method a unique name.
A controller with two methods
The example below exposes two methods. One reads data. The other changes data.
public with sharing class ContactController {
@AuraEnabled(cacheable=true)
public static List<Contact> searchContacts(String searchTerm) {
String key = '%' + searchTerm + '%';
return [
SELECT Id, Name, Email
FROM Contact
WHERE Name LIKE :key
WITH USER_MODE
ORDER BY Name
LIMIT 20
];
}
@AuraEnabled
public static void updateEmail(Id contactId, String email) {
try {
Contact c = new Contact(Id = contactId, Email = email);
update as user c;
} catch (DmlException e) {
throw new AuraHandledException(e.getDmlMessage(0));
}
}
}Points to notice:
searchContactsusescacheable=true. It only reads data, so the platform may store the result on the client.updateEmailhas nocacheableoption. It performs DML (data manipulation language, meaning insert, update, or delete), and a cacheable method must not do that.- Both methods are
static, and the class is declaredwith sharing. - Parameter names matter. The LWC will pass an object with keys
searchTerm,contactId, andemail.
Choosing cacheable
Use cacheable=true only when the method has no side effects. The platform enforces this. If a cacheable method attempts DML, the call fails at run time.
| Method does | Set cacheable=true? |
|---|---|
| Only queries records | Yes, if stale results are acceptable for a short time |
| Inserts, updates, or deletes | No |
| Calls out to an external service and changes state | No |
Wire adapters require cacheable=true. Imperative calls work with either setting. The later chapter on caching covers the trade-off in detail.
Common errors
- Missing
static. The method is not exposed, and the component import fails. - DML in a cacheable method. The call fails with an error about DML not being allowed.
- Non-serializable return type. Returning a type the platform cannot convert to JSON gives an empty or failed result.
- Overloaded names. Two methods with the same name in one class are ambiguous to the client.
Server-side errors
Inside updateEmail, a DmlException is caught and rethrown as an AuraHandledException. Other exception types reach the browser with a generic message. AuraHandledException lets you control the text the component receives. A later chapter covers this in detail.
Exercise
You write @AuraEnabled public static void deleteContact(Id contactId) { delete as user new Contact(Id = contactId); }. Should it use cacheable=true? Give the reason.
Show answer
No. The method performs DML, and cacheable methods must not change data. The platform rejects DML in a cacheable method at run time. Leave the annotation as plain @AuraEnabled.
Exercise
A teammate declares @AuraEnabled public List<Account> getAccounts() without static. What happens, and how do you fix it?
Show answer
The method is not exposed to the component, so importing it fails. Fix it by declaring it public static List<Account> getAccounts().