Sub topic 10
Navigating between pages and records
This chapter covers moving visitors between pages and records in an Experience Cloud site from a Lightning web component. It assumes you can build a basic component, that you have read the earlier chapters on exposing components and on guest security, and that you know what a Salesforce record Id is.
How navigation works in a site
A component should not build URLs by hand or assign window.location. Site URLs include a site prefix, and they can change when an admin renames a page or when the site moves between sandbox and production. Hand-built paths break when that happens.
The lightning/navigation module takes a page reference. A page reference is a plain JavaScript object that names a destination by type, attributes, and optionally state. The site runtime turns that object into a real URL and performs the navigation.
Two pieces do the work:
NavigationMixinis a function you wrap aroundLightningElement. It adds two methods to your class:NavigationMixin.NavigateandNavigationMixin.GenerateUrl.CurrentPageReferenceis a wire adapter that gives your component the page reference of the page it is on.
flowchart TDThe diagram below shows the flow from a click to a rendered page.
Navigating to a record page
The simplest case is a component that sends the visitor to a record. This is the CaseLink component from the plan for this tutorial.
import { LightningElement } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';
export default class CaseLink extends NavigationMixin(LightningElement) {
handleClick(event) {
this[NavigationMixin.Navigate]({
type: 'standard__recordPage',
attributes: {
recordId: event.currentTarget.dataset.id,
objectApiName: 'Case',
actionName: 'view'
}
});
}
}The record Id travels in a data-id attribute on the element. Read it from event.currentTarget, not event.target. If the user clicks a child element such as a <span> inside your button, target points to that child, which has no data-id. currentTarget is the element your handler is attached to.
A matching template for a list of cases looks like this:
<template>
<template for:each={cases} for:item="c">
<div key={c.Id}>
<a href="#" data-id={c.Id} onclick={handleClick}>{c.CaseNumber}</a>
</div>
</template>
</template>Using href="#" with a click handler works, but the browser also follows the hash. Call event.preventDefault() in the handler, or use the generated-URL approach described below.
Page reference types you will use in sites
| Type | Typical use | Key attributes |
|---|---|---|
| `standard__recordPage` | Open a record | `recordId`, `objectApiName`, `actionName` |
| `standard__objectPage` | Open an object list or home page | `objectApiName`, `actionName` |
| `comm__namedPage` | Open a named site page, such as Home or a custom page | `name` |
| `standard__namedPage` | Open a standard page, such as login or home | `pageName` |
| `standard__webPage` | Open an external URL | `url` |
The comm__ types exist only in Experience Cloud. The value of name in comm__namedPage is the API name of the page, which you can see in Experience Builder under the page's properties. Custom pages usually end in __c, for example Contact_Support__c.
Not every type works the same way in both runtimes. Aura sites and LWR sites support different sets of page types and actions. Check the Salesforce documentation for your runtime before you rely on a type, and test it in a published preview.
import { LightningElement } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';
export default class SupportButtons extends NavigationMixin(LightningElement) {
goToSupport() {
this[NavigationMixin.Navigate]({
type: 'comm__namedPage',
attributes: {
name: 'Contact_Support__c'
}
});
}
goToDocs() {
this[NavigationMixin.Navigate]({
type: 'standard__webPage',
attributes: {
url: 'https://help.example.com/docs'
}
});
}
}The Contact_Support__c page name is an example. Replace it with a page that exists in your site.
Generating a URL instead of navigating
GenerateUrl returns a promise that resolves to a URL string. Use it when you want a real link that visitors can open in a new tab, copy, or bookmark. It is also better for accessibility, because a screen reader announces an anchor with an href as a link.
import { LightningElement, api } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';
export default class CaseAnchor extends NavigationMixin(LightningElement) {
@api recordId;
@api label;
url;
connectedCallback() {
this[NavigationMixin.GenerateUrl]({
type: 'standard__recordPage',
attributes: {
recordId: this.recordId,
objectApiName: 'Case',
actionName: 'view'
}
}).then((generatedUrl) => {
this.url = generatedUrl;
});
}
}<template>
<a href={url}>{label}</a>
</template>Until the promise resolves, url is undefined and the anchor has no destination. That is brief, but do not assume the value exists in connectedCallback.
Passing and reading state
A page reference can carry a state object, which appears in the URL as query parameters. In a site, custom keys must start with the c__ prefix. The runtime drops or rejects other keys.
Sending side:
this[NavigationMixin.Navigate]({
type: 'comm__namedPage',
attributes: { name: 'Case_Search__c' },
state: { c__status: 'Open' }
});Receiving side, on the target page:
import { LightningElement, wire } from 'lwc';
import { CurrentPageReference } from 'lightning/navigation';
export default class CaseSearch extends LightningElement {
status;
@wire(CurrentPageReference)
handlePageReference(pageRef) {
if (pageRef && pageRef.state) {
this.status = pageRef.state.c__status;
}
}
}State values are strings. If you need a number or a boolean, convert it yourself. State is also visible and editable by the visitor, so treat it as untrusted input. Validate it in your Apex method, and never use it as a substitute for sharing rules.
Guests and navigation
A page reference only describes a destination. It does not grant access to it. A guest user who navigates to a record page for a Case sees an error or a login redirect unless the guest profile and sharing rules allow that record. The earlier chapter on guest security covers those settings.
This affects component design:
- Hide or replace links the visitor cannot use. The
isGuestcheck from theCaseListcomponent works well here. - To send a guest to the login page, use a named page reference rather than a hard-coded path. The page name differs between runtimes, so check what your site exposes.
- Do not rely on a failed navigation as a security check. Enforce access in Apex with
with sharingandWITH USER_MODE.
Common errors
- Forgetting the mixin. Calling
this[NavigationMixin.Navigate]on a class that extends plainLightningElementthrows a TypeError, because the method is not defined. Wrap the base class:NavigationMixin(LightningElement). - Reading
event.target.dataset.id. This givesundefinedwhen the click lands on a child element. UsecurrentTarget. - Missing
c__on state keys. The value never arrives on the target page. - Wrong page API name.
comm__namedPagewith a name that does not exist leaves the visitor on the current page or shows an error. Copy the name from Experience Builder. - Navigating in a wire handler or
renderedCallbackwithout a guard. This can cause a redirect loop. Navigate in response to a user action, or guard with a flag. - Testing only as an admin. An admin in Experience Builder preview can open records that a guest or an external user cannot. Test as each user type.
Testing navigation in Jest
In Jest, the lightning/navigation module is replaced by a stub from @salesforce/sfdx-lwc-jest. The stub gives you Navigate and GenerateUrl mocks that record the page reference you passed in. In a component test, trigger the click, then read the recorded page reference from the stub and compare it with the one you expect. That lets you check type, attributes, and state without running a site. The testing chapter covers the setup.
Exercise
A component handler reads event.target.dataset.id and navigates to a record page. Clicking the text inside a nested <span> in the link sometimes navigates with no record Id. What causes this, and what is the fix? Also, which prefix must a custom key in state carry in a site?
Show answer
event.target is the element that was actually clicked, which can be the nested <span>. The <span> has no data-id, so dataset.id is undefined. event.currentTarget is the element the handler is attached to, which holds the data-id, so use event.currentTarget.dataset.id. Custom state keys must start with c__, for example c__status.
Exercise
You want a link to a Case that visitors can open in a new tab. Which NavigationMixin method do you use, what does it return, and why is the href possibly empty at first?
Show answer
Use NavigationMixin.GenerateUrl. It returns a promise that resolves to a URL string. The promise resolves asynchronously, so the property bound to href is undefined until the .then() callback assigns it.