Sub topic 1
Exposing an Apex method with @AuraEnabled
This chapter covers the server side of an imperative call. You will write an Apex method that a Lightning Web Component (LWC) can reach, and you will learn which rules decide whether the platform accepts it. Later chapters import and call the method from JavaScript.
Prerequisites
This chapter assumes you can already do the following:
- Read and write basic Apex classes, methods, and SOQL queries.
- Write a Lightning Web Component with a template, a JavaScript class, and an event handler.
- Use JavaScript objects and Promises at a basic level.
- Deploy code to a scratch org or sandbox with the Salesforce CLI or an IDE.
You do not need to know how to import or call Apex yet. That comes in the next chapters.
What @AuraEnabled does
An LWC runs in the browser. Apex runs on the Salesforce server. The browser cannot call an Apex method directly, so the platform needs a way to mark which methods are reachable from client code.
The @AuraEnabled annotation is that marker. It makes a method available to Lightning components, both Aura components and LWC. The name comes from the Aura framework, which introduced it first. LWC reuses it.
A method that lacks the annotation cannot be imported into a component. A method with it can be called by anyone who can run your component, so treat every such method as a public endpoint.
The rules for an exposed method
An @AuraEnabled method for LWC must follow these rules:
- It must be
static. - It must be
publicorglobal. - It must be in a class that the calling user can access. For a custom class, that means the user's profile or a permission set grants access to the Apex class.
- Its parameters and return type must be types the platform can serialize to JSON, such as primitives,
sObjecttypes, collections, and Apex classes with annotated members.
If you break the first two rules, the code will not save or the import will fail in the component.
A first example
The following controller has two methods. One reads data and one changes it.
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));
}
}
}Both methods are public static and carry @AuraEnabled. The class is declared with sharing. The sections below explain each choice.
The cacheable option
@AuraEnabled(cacheable=true) tells the platform that the method only reads data. The client may then store the result and reuse it. The default is cacheable=false.
Use cacheable=true when both of these hold:
- The method does not change any data. It performs no DML (Data Manipulation Language) statements such as
insert,update,delete, orupsert. - It is acceptable for the caller to see a stored result for a short time instead of a fresh one.
The platform enforces the first condition. If a cacheable method runs DML, the call fails with an error. That is why updateEmail in the example has no cacheable option.
The second condition is a design decision. A cached result can be stale if another user or process changes the records. Chapter content later in this tutorial covers refreshing in detail. For now, remember the choice:
| Question | `cacheable=true` | `cacheable=false` (default) |
|---|---|---|
| Can the method do DML? | No | Yes |
| Can a wire adapter use it? | Yes | No |
| Can an imperative call use it? | Yes | Yes |
| Is the result possibly reused from the client cache? | Yes | No |
A cacheable method works in both modes. A non-cacheable method works only imperatively. So if you plan to use the method with the wire service, it must be cacheable.
Choosing sharing and access modes
The class and its queries decide which records and fields the user can see. An exposed method runs on the server with whatever access you give it.
Sharing keywords
with sharingmakes the class respect the running user's record access, such as ownership, role hierarchy, and sharing rules.without sharingignores those rules.inherited sharinguses the sharing setting of the calling code. When an LWC calls the class directly, it behaves aswith sharing.
For a controller that serves a component, start with with sharing. Switch to something else only with a clear reason, and document it.
Field-level security and object permissions
Sharing controls records. It does not control fields or object access. Two common ways to enforce those:
WITH USER_MODEin SOQL andas userin DML, as in the example. These apply object permissions and field-level security (FLS) of the running user. If the user lacks access, the platform throws an exception.WITH SECURITY_ENFORCEDin SOQL, an older option that checks fields in the query and throws on a violation.USER_MODEis the newer option and covers more cases.
A field the user cannot read causes an exception in USER_MODE. It does not silently return null. If you want to filter fields instead of failing, use Security.stripInaccessible, which removes inaccessible fields from the records.
Parameters and return types
Parameters arrive from JavaScript as values, so the platform converts them to Apex types.
| JavaScript value | Typical Apex parameter type |
|---|---|
| string | `String`, or `Id` if it is a valid record ID |
| number | `Integer`, `Decimal`, `Double`, `Long` |
| boolean | `Boolean` |
| array | `List<T>` or `Set<T>` |
| object | `Map<String, Object>`, an `sObject`, or an Apex class |
Parameter names matter. The JavaScript caller passes an object whose keys must match the Apex parameter names exactly, including case. If you rename searchTerm in Apex, every caller breaks until it is updated. The next chapters show the caller side.
The return value is serialized to JSON. Some details to know:
sObjectresults include only the fields you queried, plusId.- A related record appears as a nested object, for example
Account.Name. - Apex class instances serialize only members marked with
@AuraEnabled.
To return a custom shape, define a wrapper class with annotated members:
public with sharing class ContactSummaryController {
public class ContactSummary {
@AuraEnabled public Id id;
@AuraEnabled public String displayName;
@AuraEnabled public Integer openCases;
}
@AuraEnabled(cacheable=true)
public static List<ContactSummary> getSummaries(Id accountId) {
List<ContactSummary> results = new List<ContactSummary>();
for (Contact c : [
SELECT Id, Name, (SELECT Id FROM Cases WHERE IsClosed = false)
FROM Contact
WHERE AccountId = :accountId
WITH USER_MODE
ORDER BY Name
LIMIT 50
]) {
ContactSummary s = new ContactSummary();
s.id = c.Id;
s.displayName = c.Name;
s.openCases = c.Cases.size();
results.add(s);
}
return results;
}
}Without @AuraEnabled on id, displayName, and openCases, those members would be missing from the JSON the component receives.
Reporting failures
An uncaught exception in an @AuraEnabled method reaches the client, but the message is often generic, such as "Script-thrown exception". To control the message, catch the error and throw AuraHandledException.
@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));
}
}getDmlMessage(0) returns the message for the first failed row, such as a validation rule text. That is a message a user can act on.
A known quirk applies. AuraHandledException created with only a message can return that message to the client, but getMessage() inside Apex tests may return "Script-thrown exception". To make the message readable in both places, create the exception, then call setMessage:
AuraHandledException ex = new AuraHandledException(message);
ex.setMessage(message);
throw ex;Do not put secrets, stack traces, or internal record details in the message. The text reaches the browser.
Design guidance
- Keep each method focused. One method reads, another writes.
- Give methods clear names, since the name becomes part of the import path.
- Limit result size with
LIMITand filters, because the response travels over the network. - Avoid
@AuraEnabledon properties or methods that are not needed by any component. - Put business logic in separate service classes and keep the controller thin. This makes the logic testable and reusable.
How it fits together
The diagram shows what happens when a component reaches an exposed method.
Common mistakes
- Forgetting
static. The method then cannot be exposed. - Using DML in a
cacheable=truemethod. - Relying on
with sharingalone and skipping FLS enforcement. - Returning an Apex class whose members lack
@AuraEnabled, which leaves them out of the JSON. - Forgetting to grant users access to the Apex class through a profile or permission set. The component then fails for everyone except admins.
- Changing a parameter name without updating callers.
Exercise
A teammate writes @AuraEnabled(cacheable=true) public static void archiveContact(Id contactId), which sets a field on the contact and runs update as user. Name two problems with this design and describe a fix.
Show answer
First, a cacheable method must not perform DML, so the update fails at run time. Second, the method changes data, so reusing a cached result makes no sense. The fix is to remove cacheable=true and keep the method as a plain @AuraEnabled method. Call it imperatively, and wrap the DML in try/catch so a DmlException becomes an AuraHandledException with a readable message.
Exercise
A component receives contacts from your Apex controller, but a custom field Region__c you queried is missing for some users, and others get an error. Which query setting is likely in use, and what are your options?
Show answer
The query probably uses WITH USER_MODE (or WITH SECURITY_ENFORCED), which enforces field-level security. Users without read access to Region__c cause an exception. Options: grant the field through a permission set, or use Security.stripInaccessible to remove the field for those users instead of failing, and make the component handle a missing value.