Sub topic 8
Writing Apex for site components
This chapter assumes you can read basic Apex and SOQL. It also assumes you know how profiles, sharing rules, and permission sets control access in Salesforce. You should already have a Lightning web component that calls Apex. The chapter covers how to write the Apex class that sits behind a site component. It also covers the access settings that class needs, and the mistakes that most often break it for site users.
Why site Apex needs extra care
A component on an Experience Cloud site runs for people who are not internal users. They may be guest users (not logged in) or external users (logged in through a Customer Community, Partner Community, or similar license). Apex runs in system context by default. It ignores object permissions, field-level security, and sharing unless you ask it to enforce them. If a method returns data without those checks, an external user may see records they should not.
Two settings control this in your code:
- The sharing keyword on the class (
with sharing,without sharing, orinherited sharing) controls record-level access. WITH USER_MODEin SOQL, orAccessLevel.USER_MODEin DML, enforces object permissions and field-level security as well as sharing.
A minimal controller
This controller returns the most recent cases for the current site user.
public with sharing class CaseListController {
@AuraEnabled(cacheable=true)
public static List<Case> getMyCases(Integer maxRows) {
return [
SELECT Id, CaseNumber, Subject, Status
FROM Case
WITH USER_MODE
ORDER BY CreatedDate DESC
LIMIT :maxRows
];
}
}Points to notice:
public with sharingmakes the query respect the sharing rules of the running user.WITH USER_MODEmakes the query fail with aQueryExceptionif the user lacks read access toCaseor to any selected field. It does not silently drop fields. The olderWITH SECURITY_ENFORCEDclause is stricter in some cases and less complete in others, so preferUSER_MODEfor new code.@AuraEnabledmakes the method callable from Lightning web components. The name is historical and applies to LWC too.cacheable=trueallows the method to be used with@wireand lets the client cache the result. It also forbids DML inside the method.maxRowsarrives from the component's design property, so it is input from the client.
Wire versus imperative calls
The two call styles have different rules for the Apex method.
| Aspect | `@wire` | Imperative call |
|---|---|---|
| Requires `cacheable=true` | Yes | No |
| Can perform DML | No | Yes, if not cacheable |
| Runs when | Parameters change | You call it, for example on a button click |
| Result shape | `{ data, error }` | Promise that resolves or rejects |
Use a cacheable method for reads. Use a separate non-cacheable method for creates and updates. Mixing them in one method is not allowed, because a cacheable method cannot change data.
Calling the method from the component
The component below passes the maxRows property from the page editor to the Apex method. The wire service reruns the method when that value changes.
import { LightningElement, api, wire } from 'lwc';
import isGuest from '@salesforce/user/isGuest';
import getMyCases from '@salesforce/apex/CaseListController.getMyCases';
export default class CaseList extends LightningElement {
@api maxRows = 5;
isGuest = isGuest;
@wire(getMyCases, { maxRows: '$maxRows' })
cases;
get hasCases() {
return Boolean(this.cases && this.cases.data && this.cases.data.length);
}
}The $ prefix marks the parameter as reactive. If maxRows is undefined, the wire service does not call Apex. This is a common reason for a wire that appears to do nothing.
Never trust client input
Anything the component sends to Apex can be altered. A visitor can call your @AuraEnabled method directly with any parameters, regardless of what your UI allows. Validate on the server.
The next version of the controller clamps maxRows and handles a null value.
public with sharing class CaseListController {
private static final Integer DEFAULT_ROWS = 5;
private static final Integer MAX_ROWS = 50;
@AuraEnabled(cacheable=true)
public static List<Case> getMyCases(Integer maxRows) {
Integer safeRows = (maxRows == null || maxRows < 1)
? DEFAULT_ROWS
: Math.min(maxRows, MAX_ROWS);
return [
SELECT Id, CaseNumber, Subject, Status
FROM Case
WITH USER_MODE
ORDER BY CreatedDate DESC
LIMIT :safeRows
];
}
}Bind variables such as :safeRows are safe from SOQL injection. If you build a query as a string for Database.query, use Database.queryWithBinds with AccessLevel.USER_MODE, or escape values with String.escapeSingleQuotes. Prefer binds.
Handling errors for the component
An uncaught exception reaches the browser as a generic error. Throw an AuraHandledException when you want the component to show a useful message.
public with sharing class CaseActionController {
@AuraEnabled
public static Case closeCase(Id caseId) {
try {
Case c = [
SELECT Id, Status
FROM Case
WHERE Id = :caseId
WITH USER_MODE
];
c.Status = 'Closed';
update as user c;
return c;
} catch (QueryException e) {
throw new AuraHandledException('You cannot access this case.');
} catch (DmlException e) {
throw new AuraHandledException('The case could not be closed.');
}
}
}update as user c runs the DML in user mode, so field-level security applies to the write. Without it, the update would run in system mode.
Do not put internal details such as stack traces or record IDs from other users in the message. Guests and external users see this text.
Granting access to the class
Writing the class is not enough. The site user's profile or a permission set must allow the Apex class. Without that, the component fails with an error about access to the Apex class.
- For logged-in external users, add the class to a permission set assigned to them, or to their profile.
- For guest users, add the class to the guest user profile of the site. Open it from Workspaces, then Administration, then Pages or Settings, and use the guest user profile link.
- Guest profiles cannot receive permission sets in the same way as other profiles, and guest access to objects is limited. Give guests read access only to what the page needs.
Object and field access must also exist, because USER_MODE checks them. A class that is allowed but queries a field the profile cannot read will throw.
Guest users and sharing
Guests have extra restrictions. Salesforce does not let guest users own records by default, and guest access to records comes from guest user sharing rules. A with sharing query as a guest returns only records that a guest sharing rule exposes. Treat guest sharing rules as public data and keep them narrow.
For records that belong to a logged-in customer, such as "my cases", guests should see nothing. The component in this tutorial hides the list for guests, but that is only a convenience. The real protection is server side. You can add an explicit check as well.
public with sharing class CaseListController {
@AuraEnabled(cacheable=true)
public static List<Case> getMyCases(Integer maxRows) {
if (UserInfo.getUserType() == 'Guest') {
throw new AuraHandledException('Log in to see your cases.');
}
Integer safeRows = (maxRows == null || maxRows < 1)
? 5
: Math.min(maxRows, 50);
return [
SELECT Id, CaseNumber, Subject, Status
FROM Case
WITH USER_MODE
ORDER BY CreatedDate DESC
LIMIT :safeRows
];
}
}Request flow
The diagram shows what happens on each call and where each check applies.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| "You do not have access to the Apex class" | Class not enabled for the profile or permission set | Add the class to the guest profile or a permission set |
| `QueryException` about field access | `USER_MODE` found a field the user cannot read | Grant field-level security, or remove the field |
| Component works for admins, fails for site users | Admin has broad access, site user does not | Test as a real external user and as a guest |
| Wire never fires | A reactive parameter is `undefined` | Set a default value for the property |
| "Method must be cacheable" style error on wire | `cacheable=true` missing | Add it, or call imperatively |
| DML error in a cacheable method | Cacheable methods cannot change data | Move the DML to a separate non-cacheable method |
| Stale data after an update | Cached wire result | Call `refreshApex` on the wired result |
Keeping classes small
Keep one controller per feature and keep it thin. Put reusable query logic in a separate class, and make that class inherited sharing so it takes on the sharing mode of its caller. A shared without sharing helper called from a with sharing controller is a frequent source of accidental over-exposure, so avoid it unless you have a documented reason.
Exercise
A guest visits a page that uses your cacheable Apex method. The class is with sharing and the SOQL uses WITH USER_MODE, but the call fails with an access error before any query runs. What is the most likely cause, and where do you fix it?
Show answer
The Apex class is not enabled for the site's guest user profile. Add the class to that profile through the site's Administration settings. Also confirm the guest profile has read access to the object and fields, because USER_MODE will check those next.
Exercise
Why is hiding the case list in the template with isGuest not enough to protect the data?
Show answer
The check runs in the browser, and a visitor can call the @AuraEnabled method directly with their own parameters. The protection must come from server-side controls: sharing, WITH USER_MODE, class access, and an optional explicit user type check in Apex.