Sub topic 6
Reading site and user context
This chapter assumes you can build a basic Lightning web component and read a wire adapter. You should also know how a site user differs from an internal user. After this chapter, you will know how to find out who is viewing a page, which site they are on and what device and language they use. You will also know where this information is reliable and where it is not.
Why components need context
A component on an Experience Cloud site runs for many kinds of visitors. A guest sees the page without logging in. An external user logs in with a Customer Community or Partner Community license. An administrator previews the page in Experience Builder. The same component often has to behave differently for each of them. It might show a login prompt, hide a button or build a link relative to the site's URL.
LWC provides this information through scoped module imports. You import a value from a path that starts with @salesforce/. The platform resolves the import when the module loads. You do not call an API or wait for a response.
The context imports
| Import | Type | What it gives you |
|---|---|---|
| `@salesforce/user/Id` | String | The Id of the current user. For a guest, this is the Id of the site's guest user record. |
| `@salesforce/user/isGuest` | Boolean | `true` when the visitor is not logged in. |
| `@salesforce/community/Id` | String | The Id of the current Experience Cloud site. |
| `@salesforce/community/basePath` | String | The URL path prefix of the site, such as `/s` on many Aura sites. |
| `@salesforce/i18n/lang` | String | The language code of the user, such as `en-US`. |
| `@salesforce/i18n/locale` | String | The locale used for dates and numbers. |
| `@salesforce/client/formFactor` | String | `Large`, `Medium` or `Small`, based on the device. |
Each import is a default export. You can name it anything:
import IS_GUEST from '@salesforce/user/isGuest';How these imports behave
Three properties of these imports cause most of the mistakes.
- They are constants. The value is fixed when the module loads. If a user logs in, the browser navigates to an authenticated page and the module loads again. You never need to watch for
isGuestchanging inside one page view. - They are not reactive wire inputs by themselves. Copy the value into a class field or getter before you use it in a template. You can use a getter as a
$parameter in a wire configuration. - The guest user Id is a real Id.
@salesforce/user/Idis not empty for guests. Checkingif (USER_ID)will not tell you whether someone is logged in. UseisGuest.
flowchart TD
A[Component module loads] --> B{isGuest?}
B -- true --> C[Show login prompt, skip user queries]
B -- false --> D[Use user Id in wire adapters]
D --> E[getRecord for User fields]
A --> F[basePath and site Id for links and branding]The diagram above shows the usual decision. Check isGuest first, then fetch data only for logged-in users.
A component that shows its context
The component below displays the context values and loads the current user's name. It does not request the name for guests.
import { LightningElement, wire } from 'lwc';
import { getRecord, getFieldValue } from 'lightning/uiRecordApi';
import USER_ID from '@salesforce/user/Id';
import IS_GUEST from '@salesforce/user/isGuest';
import SITE_ID from '@salesforce/community/Id';
import BASE_PATH from '@salesforce/community/basePath';
import LANG from '@salesforce/i18n/lang';
import FORM_FACTOR from '@salesforce/client/formFactor';
import NAME_FIELD from '@salesforce/schema/User.Name';
export default class SiteContext extends LightningElement {
isGuest = IS_GUEST;
siteId = SITE_ID;
basePath = BASE_PATH;
lang = LANG;
formFactor = FORM_FACTOR;
// An undefined parameter stops the wire from provisioning data.
get userRecordId() {
return IS_GUEST ? undefined : USER_ID;
}
@wire(getRecord, { recordId: '$userRecordId', fields: [NAME_FIELD] })
user;
get userName() {
return this.user && this.user.data
? getFieldValue(this.user.data, NAME_FIELD)
: undefined;
}
get isSmallScreen() {
return FORM_FACTOR === 'Small';
}
}<template>
<lightning-card title="Site context">
<div class="slds-var-p-around_medium">
<template lwc:if={isGuest}>
<p>You are browsing as a guest.</p>
</template>
<template lwc:else>
<p>Welcome, {userName}.</p>
</template>
<p>Site Id: {siteId}</p>
<p>Base path: {basePath}</p>
<p>Language: {lang}</p>
<p>Form factor: {formFactor}</p>
</div>
</lightning-card>
</template><?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>60.0</apiVersion>
<isExposed>true</isExposed>
<masterLabel>Site Context</masterLabel>
<targets>
<target>lightningCommunity__Page</target>
<target>lightningCommunity__Default</target>
</targets>
</LightningComponentBundle>When userRecordId is undefined, the wire adapter does not run. The component makes no failing request for the guest user. This pattern replaces a manual if (!isGuest) check inside a method.
Reading more than the Id
The Id alone says little about the user. To read fields such as Name, Contact.AccountId or a custom field, use getRecord with the user Id, as shown above. Import each field from @salesforce/schema so the platform can check that the field exists and track the dependency.
Keep these limits in mind:
- Field access still follows the user's permissions. An external user may not be able to read some
Userfields. If a field is hidden,getFieldValuereturnsundefined, and the template should handle that. - Fields on related records, such as
User.Contact.Account.Name, require access to those related records through sharing and field-level security. - For data that the User object cannot provide under the site's sharing model, write an Apex method. The chapter on Apex for site components covers this.
Using basePath for links
basePath helps when you need a URL string, for example for an anchor tag that opens a login page:
import BASE_PATH from '@salesforce/community/basePath';
export default class LoginLink {
get loginUrl() {
return `${BASE_PATH}/login`;
}
}This works when you know the site's URL structure. Aura and LWR sites build their paths differently, and a site can use a custom prefix. Test the generated URL on each site you support. Where possible, prefer NavigationMixin over hand-built URLs, because it resolves the target for the current site. For login, use type: 'comm__loginPage' with attributes: { actionName: 'login' }. The navigation chapter explains this API.
Preview behaves differently from the live site
In Experience Builder, the page runs for the user who is editing it. That is usually an administrator, so isGuest is false in the editor even if the published page will treat visitors as guests. To check the guest experience, publish the site and open it in a private browser window, or use the preview option that simulates a guest if your org offers it. A component that looks correct in the editor can still show the wrong branch to real guests.
Testing components that use context imports
Jest cannot resolve these imports in every setup. Mock them with virtual: true so the test runs without the platform:
import { createElement } from 'lwc';
import SiteContext from 'c/siteContext';
jest.mock('@salesforce/user/isGuest', () => ({ default: true }), { virtual: true });
jest.mock('@salesforce/user/Id', () => ({ default: '005000000000001AAA' }), { virtual: true });
jest.mock('@salesforce/community/Id', () => ({ default: '0DM000000000001AAA' }), { virtual: true });
jest.mock('@salesforce/community/basePath', () => ({ default: '/s' }), { virtual: true });
describe('c-site-context', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('shows the guest message', () => {
const element = createElement('c-site-context', { is: SiteContext });
document.body.appendChild(element);
const text = element.shadowRoot.textContent;
expect(text).toContain('You are browsing as a guest.');
expect(text).toContain('/s');
});
});To test the logged-in branch, change the mocked isGuest value in a separate test file. Jest evaluates jest.mock once per file.
Common errors
- Checking
USER_IDfor truthiness. It is always set, even for guests. UseisGuest. - Expecting the editor to match the live site. The editor runs as the builder user.
- Hard-coding
/s. Not every site uses that prefix. ImportbasePathor useNavigationMixin. - Requesting user fields for guests. The request fails or returns nothing. Skip the wire when
isGuestistrue. - Forgetting to mock imports in Jest. The test fails at import time with a module resolution error.
Exercise
A component imports USER_ID from @salesforce/user/Id and shows a "Welcome back" banner when USER_ID has a value. Visitors who are not logged in also see the banner. Why does this happen, and how do you fix it?
Show answer
The guest user is a real user record, so @salesforce/user/Id returns its Id and the value is always truthy. Import @salesforce/user/isGuest and show the banner only when isGuest is false.
Exercise
You want a component to load the current user's Name with getRecord, but only for logged-in users. How do you write the wire configuration so no request goes out for guests?
Show answer
Create a getter such as get userRecordId() { return IS_GUEST ? undefined : USER_ID; } and use @wire(getRecord, { recordId: '$userRecordId', fields: [NAME_FIELD] }). A wire adapter does not run while a reactive parameter is undefined.
Exercise
A developer tests a component in Experience Builder and sees the logged-in layout. After publishing, guests see the login prompt. Is this a bug in the component?
Show answer
No. The editor runs as the user who is editing the page, so isGuest is false there. The published site runs for the real visitor. Verify the guest experience in a private browser window on the published site.