Sub topic 1
Exposing Apex to LWC with @AuraEnabled(cacheable=true)
A Lightning web component runs in the browser. Your SOQL queries and business logic run on the Salesforce server. The @AuraEnabled annotation is how an Apex method becomes callable from a component, and the cacheable=true option makes that method usable with @wire. This chapter covers how to write such a method, the rules the platform enforces, and the mistakes that cause the most confusion.
Prerequisites
This chapter assumes you have:
- Basic Apex syntax and SOQL, including bind variables such as
:accountId. - A working idea of how a Lightning web component is structured: an HTML template, a JavaScript class, and
@apiproperties. - Basic JavaScript, including ES modules and destructuring.
- A Salesforce org or scratch org where you can deploy Apex classes.
You do not need to write any JavaScript in this chapter. The next chapters import and wire the method you build here.
What the annotation does
@AuraEnabled marks a method as reachable from client-side code. Without it, a component cannot import the method. The cacheable=true option adds a promise about the method: it only reads data and never changes it. The platform uses that promise in two ways.
- It allows
@wireto call the method. Wire adapters can only provision data from cacheable methods. - It lets the client store results and reuse them. A repeated call with the same parameters can be answered without a server round trip.
The second point shapes how you design the method. A cacheable method may return stale data, so it must never be the place where you save a record or trigger a side effect.
Anatomy of a cacheable method
This controller returns the contacts for an account. It is the method the rest of the tutorial wires to a component.
public with sharing class ContactController {
@AuraEnabled(cacheable=true)
public static List<Contact> getContacts(Id accountId) {
return [
SELECT Id, Name, Email
FROM Contact
WHERE AccountId = :accountId
WITH USER_MODE
ORDER BY Name
LIMIT 50
];
}
}Each part of this class has a purpose.
public with sharing classmakes the class's queries respect record sharing for the running user.@AuraEnabled(cacheable=true)exposes the method to LWC and marks it read-only.staticis required. The platform calls the method without creating an instance of the class.publicmakes the method visible to your own org's components.globalis only needed for managed packages that expose the method to other namespaces.Id accountIdis the parameter. The component passes an object whose property names match parameter names.WITH USER_MODEenforces the user's object permissions and field-level security on the query.LIMIT 50keeps the payload small. Everything returned is serialized to JSON and sent to the browser.
Rules the platform enforces
| Rule | What happens if you break it |
|---|---|
| The method must be `static` | The class fails to save or the method is not callable |
| The method must be `public` or `global` | The component cannot import it |
| No DML in a cacheable method | The call throws a runtime exception |
| No overloaded `@AuraEnabled` methods | Only one method per name is allowed. Give each method its own name. |
| Parameter names must match the keys the component passes | The value arrives as `null` |
| Return values must be serializable | Fields that are not exposed are missing from the result |
The DML rule deserves attention because it fails at runtime, not at save time. The class compiles, deploys, and may even pass a test that never hits the DML path. The error appears in the browser when a user triggers it. Treat the cacheable=true annotation as a contract: queries and calculations only. If an action must insert, update, or delete, use a separate method without cacheable=true and call it imperatively. A later chapter covers that.
Parameters and return types
Parameters can be primitives such as String, Id, Integer, and Boolean. They can also be sObjects, collections of those types, or Apex classes whose exposed members are marked @AuraEnabled.
Return types follow the same rules. A List<Contact> serializes to an array of objects. Only the fields you selected in the query are populated. If the component reads contact.Phone but your SOQL does not select Phone, the value is undefined in JavaScript. There is no error to point you at the cause.
When you need to shape data that does not match an sObject, return a small wrapper class. Each property you want to expose needs the annotation.
public with sharing class ContactSummaryController {
public class ContactSummary {
@AuraEnabled public Id id;
@AuraEnabled public String name;
@AuraEnabled public Boolean hasEmail;
}
@AuraEnabled(cacheable=true)
public static List<ContactSummary> getSummaries(Id accountId) {
List<ContactSummary> result = new List<ContactSummary>();
for (Contact c : [
SELECT Id, Name, Email
FROM Contact
WHERE AccountId = :accountId
WITH USER_MODE
ORDER BY Name
LIMIT 50
]) {
ContactSummary summary = new ContactSummary();
summary.id = c.Id;
summary.name = c.Name;
summary.hasEmail = String.isNotBlank(c.Email);
result.add(summary);
}
return result;
}
}A wrapper keeps the response small and hides fields the component should not see. It also adds code to maintain, so use one when the shape really differs from the sObject.
Security belongs in the method
Exposing a method to LWC does not add any security. Any authenticated user who can run the class can call the method with any parameter values. Treat every parameter as untrusted input.
- Declare the class
with sharingso record visibility follows the sharing model. A class with no sharing keyword inherits the mode of its caller, and that is not always what you expect. - Use
WITH USER_MODEin SOQL so the query also enforces object permissions and field-level security. If the user cannot read a selected field, the query throws aQueryException. It does not silently drop the field. - Use bind variables such as
:accountId. For dynamic SOQL, bind variables orString.escapeSingleQuotesprotect against injection. - Keep the field list to what the component needs.
The tutorial returns to sharing and field-level security in its own chapter. For now, the habit to form is writing with sharing and WITH USER_MODE the first time you write the method, not as a later cleanup.
Reporting errors
When a method fails, the component receives an error object. For unexpected exceptions, the message the user sees is often generic. To control the text, catch the exception and throw an AuraHandledException with a message you set explicitly.
public with sharing class SafeContactController {
@AuraEnabled(cacheable=true)
public static List<Contact> getContacts(Id accountId) {
if (accountId == null) {
throw buildException('An account Id is required.');
}
try {
return [
SELECT Id, Name, Email
FROM Contact
WHERE AccountId = :accountId
WITH USER_MODE
ORDER BY Name
LIMIT 50
];
} catch (QueryException e) {
throw buildException('You do not have access to read these contacts.');
}
}
private static AuraHandledException buildException(String message) {
AuraHandledException ex = new AuraHandledException(message);
ex.setMessage(message);
return ex;
}
}The call to setMessage matters. Without it, getMessage() on an AuraHandledException returns a generic "Script-thrown exception" text, and so does the client. The component later reads the text from error.body.message. Avoid putting stack traces, query text, or record data in these messages, since the browser shows them.
Common errors and how to read them
- The component cannot find the method. Check that the class is deployed, the method is
staticandpublic, and the annotation is spelled@AuraEnabled(cacheable=true). The import path in the component must match the class and method names exactly. - A parameter is always
null. The key in the object the component passes does not match the Apex parameter name. Names are case-sensitive. - Fields are
undefinedin the component. The SOQL did not select them, or they were not marked@AuraEnabledin a wrapper class. - A DML error appears in the browser. A cacheable method, or something it calls, performs DML. Move the write to a non-cacheable method.
- Old data keeps appearing after an update. The client cache returned an earlier result. Later chapters cover how the cache works and how to refresh it.
- A user sees fewer records than you expect. The class uses
with sharing, so the result depends on the running user. Test as a user with the same access as your audience, not only as an administrator.
Testing the method in Apex
Write an Apex test before wiring any UI. It proves the query and the error path without a browser.
@IsTest
private class ContactControllerTest {
@IsTest
static void returnsContactsForAccount() {
Account acct = new Account(Name = 'Acme');
insert acct;
insert new List<Contact>{
new Contact(LastName = 'Adams', AccountId = acct.Id),
new Contact(LastName = 'Baker', AccountId = acct.Id)
};
Test.startTest();
List<Contact> result = ContactController.getContacts(acct.Id);
Test.stopTest();
System.assertEquals(2, result.size());
System.assertEquals('Adams', result[0].LastName);
}
@IsTest
static void returnsNothingForNullAccount() {
List<Contact> result = ContactController.getContacts(null);
System.assertEquals(0, result.size());
}
}The test runs as the user who starts it, usually with broad access. To check how the method behaves for a restricted user, create a user with a limited profile or permission set and call the method inside System.runAs.
Summary
A wired method must be static, public or global, annotated with @AuraEnabled(cacheable=true), and read-only. Declare the class with sharing, use WITH USER_MODE, return only the fields and rows the component needs, and set messages on AuraHandledException so errors are readable. With that in place, the next chapter imports the method into a component.
Exercise
A teammate adds update acct; to a method annotated @AuraEnabled(cacheable=true) so it can "mark the account as viewed" whenever the component loads. The class saves and deploys without errors. What goes wrong, and how should the code be structured instead?
Show answer
The class compiles, but the call fails at runtime in the browser. Cacheable methods are read-only, so DML is not allowed. The cache would also skip the server on repeat calls, so the update would not run reliably. Keep the read in a cacheable method. Put the update in a separate @AuraEnabled method without cacheable=true, and have the component call it imperatively, for example in response to a user action.
Exercise
A component passes { accountid: this.recordId } to a method declared as getContacts(Id accountId), and the method always returns an empty list. What is the likely cause?
Show answer
The key name accountid does not match the parameter name accountId, because the names are case-sensitive. The parameter arrives as null, so the WHERE AccountId = :accountId filter matches no rows. Change the key to accountId.