Sub topic 2
Reading Site and User Context
Assume you know basic LWC structure, JavaScript modules, Apex, SOQL, and Salesforce sharing. Experience Cloud sites run as either Aura sites or LWR sites, and context imports can differ between them.
Reading Site and User Context
A component can read whether the current visitor is a guest. A guest is a visitor who has not authenticated. It can also read the current user ID and site information through Salesforce-provided modules.
import { LightningElement } from 'lwc';
import isGuest from '@salesforce/user/isGuest';
import userId from '@salesforce/user/Id';
import communityId from '@salesforce/community/Id';
export default class VisitorContext extends LightningElement {
isGuest = isGuest;
userId = userId;
communityId = communityId;
}Use the context module that matches the site's runtime. For LWR-specific site context, use the corresponding @salesforce/site/* module where supported. Do not treat a JavaScript guest check as a security control. A visitor can call server-side code without using your component's visible interface.
Getting Data into a Component
Use @wire for reactive reads. A reactive parameter, marked with $, causes the wire adapter to run again when its value changes. Apex methods used with @wire must be cacheable.
import { LightningElement, api, wire } from 'lwc';
import getMyCases from '@salesforce/apex/CaseListController.getMyCases';
export default class CaseList extends LightningElement {
@api maxRows = 5;
@wire(getMyCases, { maxRows: '$maxRows' })
cases;
}Use an imperative Apex call when the user starts the request explicitly or when the operation changes data.
Writing Apex for Site Components
Keep the controller small and return only fields the template needs. with sharing applies record-sharing rules. WITH USER_MODE also enforces the running user's object and field permissions.
public with sharing class CaseListController {
@AuraEnabled(cacheable=true)
public static List<Case> getMyCases(Integer maxRows) {
Integer rows = Math.max(1, Math.min(maxRows == null ? 5 : maxRows, 50));
return [
SELECT Id, CaseNumber, Subject, Status
FROM Case
WITH USER_MODE
ORDER BY CreatedDate DESC
LIMIT :rows
];
}
}Securing Guest and External Users
Configure Apex class access, object permissions, field permissions, and sharing for each site user profile or permission set. Guest users should receive only intentionally public data. External authenticated users need access to records through the site's sharing model.
Exercise
Why should an LWC not rely on isGuest to protect records?
Show answer
The client-side value controls display only. Apex must enforce sharing, object access, field access, and any application-specific rules.