Sub topic 2
Importing the Apex method into your component
This chapter covers the @salesforce/apex import. It is the link between a component's JavaScript and a method in an Apex class. I assume you know ES module syntax, can write a basic LWC, and have already exposed an Apex method with @AuraEnabled, as in the previous chapter. The chapter has no call logic. It covers only how the method gets into your module and what you receive.
What the import gives you
An LWC cannot reach Apex through a URL or an HTTP client. The platform provides a special module scheme, @salesforce/apex, and the compiler resolves it when your component is built. Each import binds one Apex method to a local JavaScript function.
import searchContacts from '@salesforce/apex/ContactController.searchContacts';This line does three things:
- It tells the platform that this component depends on the method
searchContactsin the classContactController. - It creates a local binding named
searchContacts. - The binding is a function. Calling it sends a request to the server and returns a Promise.
The import does not call the server. Nothing runs until your code calls the function, or until you hand the function to @wire. The next chapter covers the call.
Anatomy of the import path
import methodName from '@salesforce/apex/[namespace.]ClassName.methodName';| Part | Meaning | Notes |
|---|---|---|
| `@salesforce/apex` | The module scheme for Apex methods | Fixed text |
| `namespace.` | Namespace prefix of the package that owns the class | Leave it out for classes in your own org without a namespace |
| `ClassName` | The Apex class | Must be an outer class |
| `methodName` | The `@AuraEnabled` static method | Must match the Apex name |
| `methodName` (local) | The name you give the binding | You choose it, but it is normally the same as the Apex name |
The import is a default import. You write no braces, and the identifier on the left is only a local alias. These two lines import the same method:
import searchContacts from '@salesforce/apex/ContactController.searchContacts';
import findPeople from '@salesforce/apex/ContactController.searchContacts';Use the Apex method name as the local name. It makes errors and stack traces easier to read, and it matches what reviewers expect.
A complete example
Here is the controller from the tutorial, with the two methods the component will use.
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));
}
}
}The component imports each method separately, one import statement per method:
import { LightningElement } from 'lwc';
import searchContacts from '@salesforce/apex/ContactController.searchContacts';
import updateEmail from '@salesforce/apex/ContactController.updateEmail';
export default class ContactEditor extends LightningElement {
contacts = [];
connectedCallback() {
// Both bindings are functions. Logging the type shows that nothing
// has been sent to the server yet.
console.log(typeof searchContacts); // "function"
console.log(typeof updateEmail); // "function"
}
}There is no way to import a whole class and then pick methods from it. import ContactController from '@salesforce/apex/ContactController' is not valid. Every method needs its own full path.
Rules the import enforces
The platform checks the import against the Apex source. Most failures show up when you deploy or build, not when a user clicks something. Check these conditions first when an import fails.
- The method must be
static. Instance methods cannot be called from a component. - The method must be
publicorglobal, and annotated with@AuraEnabled. A private method, or one without the annotation, cannot be imported. - The class must be an outer class. The path format has no way to name a nested class.
- The method must not be overloaded. Two
@AuraEnabledmethods with the same name in one class cause an error. Give them different names, for examplesearchContactsByNameandsearchContactsByEmail. - The import path must be a literal string. You cannot build the path from a variable or use a dynamic
import()with computed text. The compiler needs to see every dependency in advance. - The running user must have access to the class. Add the class to the user's profile or a permission set under Apex Class Access. Without it, the import compiles and the call fails at runtime with an access error, which can confuse developers who test as an admin.
Namespaces
If the Apex class is in a managed package, put the package's namespace before the class name, separated by a dot:
import searchContacts from '@salesforce/apex/acme.ContactController.searchContacts';If you develop inside a namespaced org, such as a packaging org, you use the same form for your own classes. If your org has no namespace, as in most scratch orgs and sandboxes, leave it out. Do not write c. or any placeholder prefix in front of the class name. That prefix is for Lightning components, not for Apex imports.
What the imported function looks like
The function you receive has a fixed contract:
- It takes zero or one argument: an object whose keys are the Apex parameter names. The next chapter covers this in detail.
- It returns a Promise. The Promise resolves with the Apex return value, converted to JSON-compatible JavaScript data. It rejects with an error object if the server throws.
- The same binding can be used in two ways: called directly (imperatively), or passed to
@wire. A wire needscacheable=trueon the method, and a direct call does not.
Because the module is a binding and not a copy of the Apex code, nothing about the Apex logic is visible to the browser. Only the method signature crosses over, and the server runs the logic.
Common mistakes
Using a named import. Writing import { searchContacts } from '@salesforce/apex/ContactController.searchContacts'; gives undefined at runtime or a build error. The module has a default export only.
Forgetting static. An instance method in the controller will not work, and the error often points at the import, not at the Apex.
Importing a method that is not annotated. If @AuraEnabled is missing, the platform does not treat the method as part of the component API.
Mixing up the argument shape. The imported function expects one object, { searchTerm: 'Ada' }. Passing the bare string 'Ada' will not map to the parameter. This belongs to the call, but you see it as soon as you use the imported function, so check for it early.
Assuming the import checks access. A successful build does not prove that every user can run the method. Class access and object and field permissions are applied at runtime, as the security section of this tutorial explains.
Deploying components before the class. If the component and class go in the same deployment, the platform sorts out the order. If you deploy the component alone to an org that lacks the class, the deployment fails. Keep the Apex class and the component in the same source package.
Where imports belong in the file
Put all imports at the top of the JavaScript file, after the lwc import. A common ordering is:
lwcand base framework imports@salesforce/apeximports@salesforce/schema, label, and other scoped module imports- imports of other component modules or helper files
The ordering is a convention, not a requirement. The binding is a constant, so you cannot assign to it later. Code such as searchContacts = somethingElse; is a syntax error in a module.
Why the import path matters for testing
Jest does not run Apex. In a unit test, the path string is the key you use to replace the import with a mock function, so the string in the test must match the string in the component. A later chapter shows how to write the mock. For now, keep import paths simple and consistent, so there is only one string to match.
Exercise
A teammate adds this import to a component and gets undefined at runtime: import { updateEmail } from '@salesforce/apex/ContactController.updateEmail';. The Apex method is @AuraEnabled public static void updateEmail(Id contactId, String email). What is wrong with the import, and what is the corrected line? Also name one Apex-side condition that would stop the import from working even with the correct syntax.
Show answer
The import uses braces, which is a named import, but the module only has a default export. The corrected line is import updateEmail from '@salesforce/apex/ContactController.updateEmail';. An Apex-side condition that would still break it: the method is not static, is private, lacks @AuraEnabled, is overloaded, or the class is nested instead of an outer class. Missing Apex class access for the user's profile or permission set also causes a runtime failure.