Sub topic 14
Navigating from a Lightning Web Component
This chapter assumes you can read basic JavaScript and have built or deployed a simple Lightning Web Component (LWC) before. You should also know the Lightning URL patterns from the previous chapter, because programmatic navigation is a structured way to reach those same destinations without writing URLs by hand.
Why not just set the URL?
You could set window.location to /lightning/r/Account/001.../view. That works poorly for three reasons.
- It forces a full page reload, so Lightning Experience restarts instead of swapping the page.
- It hard-codes URL formats that Salesforce can change. It also ignores the Experience Cloud site or console context the component runs in.
- It does not work the same way in the Salesforce mobile app, where URLs are not the navigation model.
The lightning/navigation module solves this. You describe the destination as a page reference, and the platform builds the right URL or mobile transition for the current container.
The page reference
A page reference is a plain JavaScript object with three parts.
| Part | Purpose |
|---|---|
| `type` | The kind of destination, such as `standard__objectPage` or `standard__recordPage`. |
| `attributes` | The values that identify the destination, such as an object name or record Id. |
| `state` | Optional extra parameters, such as which list view filter to apply. |
Common page reference types:
| Type | Destination | Key attributes |
|---|---|---|
| `standard__objectPage` | Object home, list view, or new-record form | `objectApiName`, `actionName` (`home`, `list`, `new`) |
| `standard__recordPage` | A record page | `recordId`, `objectApiName`, `actionName` (`view`, `edit`, `clone`) |
| `standard__recordRelationshipPage` | A related list of a record | `recordId`, `objectApiName`, `relationshipApiName`, `actionName` (`view`) |
| `standard__namedPage` | A standard page such as home or chatter | `pageName` |
| `standard__webPage` | An external URL | `url` |
The NavigationMixin
NavigationMixin is a function that wraps your base class and adds two methods, reached through symbol keys:
this[NavigationMixin.Navigate](pageRef, replace)moves the user to the destination. Ifreplaceistrue, the new page replaces the current entry in the browser history instead of adding one.this[NavigationMixin.GenerateUrl](pageRef)returns a promise that resolves to a URL string, without navigating.
The symbol keys prevent your own method names from colliding with the mixin.
Opening a list view and a record
The component below follows the spine example. The first method opens the Account Recent list view. The second opens the view page of one Account.
import { LightningElement } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';
export default class AccountNavigator extends NavigationMixin(LightningElement) {
openRecentAccounts() {
this[NavigationMixin.Navigate]({
type: 'standard__objectPage',
attributes: {
objectApiName: 'Account',
actionName: 'list'
},
state: {
filterName: 'Recent'
}
});
}
openAccount(recordId) {
this[NavigationMixin.Navigate]({
type: 'standard__recordPage',
attributes: {
recordId: recordId,
objectApiName: 'Account',
actionName: 'view'
}
});
}
}These two page references correspond to the URLs you read in the previous chapter:
/lightning/o/Account/list?filterName=Recent
/lightning/r/Account/001XXXXXXXXXXXXXXX/viewThe mapping is direct. standard__objectPage with actionName: 'list' becomes /lightning/o/Account/list. The state entry filterName becomes the query parameter. The record page reference becomes the /lightning/r/ path.
Wiring the methods to a template
The methods above are not called by anything yet. A template can call them from button clicks. For the record case, pass the Id through a data- attribute.
<template>
<lightning-card title="Account shortcuts">
<div class="slds-var-p-around_medium">
<lightning-button
label="Recent accounts"
onclick={openRecentAccounts}>
</lightning-button>
<lightning-button
label="Open account"
data-id="001XXXXXXXXXXXXXXX"
onclick={handleOpenAccount}>
</lightning-button>
</div>
</lightning-card>
</template>Event handlers receive an event, not a record Id, so openAccount(recordId) cannot be bound directly. Add a handler that reads the Id from the event:
handleOpenAccount(event) {
this.openAccount(event.target.dataset.id);
}Replace the sample Id with a real one from your org, or pass an Id that your component receives from an @api property or a wire adapter.
To make the component available on a page, give it a metadata file that exposes it:
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>60.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>Generating a URL instead of navigating
Sometimes you want a real link, so users can open it in a new tab or copy it. Use GenerateUrl and put the result in an anchor.
import { LightningElement, api } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';
export default class AccountLink extends NavigationMixin(LightningElement) {
@api recordId;
url;
connectedCallback() {
this[NavigationMixin.GenerateUrl]({
type: 'standard__recordPage',
attributes: {
recordId: this.recordId,
objectApiName: 'Account',
actionName: 'view'
}
}).then((generated) => {
this.url = generated;
});
}
handleClick(event) {
event.preventDefault();
this[NavigationMixin.Navigate]({
type: 'standard__recordPage',
attributes: {
recordId: this.recordId,
objectApiName: 'Account',
actionName: 'view'
}
});
}
}The matching template:
<template>
<a href={url} onclick={handleClick}>Open this account</a>
</template>The href supports middle-click and copy-link. The click handler cancels the default browser jump and uses Navigate instead, so the page does not fully reload.
Navigating with filters and state
The state object carries destination-specific parameters. For an object page with actionName: 'list', filterName accepts either a standard list view name such as Recent or the Id or API name of a custom list view. The list view you open is the same one a user would pick in the list view menu. Filters, sorting, and display mode all come from that saved list view.
Other uses of state include:
- Pre-populating a new record form with
defaultFieldValues, which usesnooverride: '1'alongside it. - Setting a search term on a list through
statekeys that the destination page documents.
This example opens a new Contact form with some fields pre-filled. The encodeDefaultFieldValues helper is exported by lightning/pageReferenceUtils.
import { LightningElement, api } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';
import { encodeDefaultFieldValues } from 'lightning/pageReferenceUtils';
export default class NewContactButton extends NavigationMixin(LightningElement) {
@api accountId;
handleNewContact() {
const defaults = encodeDefaultFieldValues({
AccountId: this.accountId,
LeadSource: 'Web'
});
this[NavigationMixin.Navigate]({
type: 'standard__objectPage',
attributes: {
objectApiName: 'Contact',
actionName: 'new'
},
state: {
defaultFieldValues: defaults,
nooverride: '1'
}
});
}
}Behavior in apps and consoles
Navigation depends on where the component runs.
- In a standard app,
Navigatereplaces the current page content and updates the browser URL. - In a console app, navigating to a record opens it in a new workspace tab, or focuses the tab if it is already open. This follows the console behavior described earlier in the tutorial.
- A destination that belongs to an object the current app does not list still opens. The navigation bar then shows the app's items, and the object is not highlighted.
- In an Experience Cloud site, URL formats differ, which is another reason to use page references rather than hand-built paths.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `Navigate` is not a function or `undefined` is called | The class extends `LightningElement` directly instead of `NavigationMixin(LightningElement)`. | Wrap the base class. |
| Nothing happens, or the page shows an error | A missing or misspelled `type`, `objectApiName`, or `actionName`. | Compare with the attribute table above. |
| The record page opens blank or errors | `recordId` is `undefined`, often because it was read before the component received it. | Navigate only after the Id is set, such as from a click handler or after a wire result. |
| The list opens on the wrong view | `filterName` is wrong, or the list view is not visible to the user. | Check the name or Id, and confirm sharing of the list view. |
| `this` is `undefined` inside a handler | A callback that is not an arrow function loses its context. | Use arrow functions or call handlers as class methods in the template. |
| Component does not appear in the page builder | `isExposed` is false or no targets are listed. | Fix the metadata file and redeploy. |
Design guidance
- Prefer a standard anchor with
GenerateUrlfor links, andNavigatefor button actions. - Keep page reference objects in one place if several methods use the same destination.
- Use
lightning-formatted-urlorlightning-navigationfeatures only for simple cases. Components that need control use the mixin. - Test inside a console app and in the mobile app if your users use them. Page references are designed to work in both, but the visible result differs.
Exercise
A component's button click calls this[NavigationMixin.Navigate] and throws "this[NavigationMixin.Navigate] is not a function". The class is declared as export default class Shortcuts extends LightningElement. What is the fix, and what does the mixin add?
Show answer
Declare the class as extends NavigationMixin(LightningElement). The mixin wraps the base class and adds the Navigate and GenerateUrl methods, which are reached through symbol keys. Without the wrapper, those methods do not exist on the component.
Exercise
Write the page reference that opens the Contact list view named AllContacts. Which URL from the earlier chapter does it correspond to?
Show answer
Use { type: 'standard__objectPage', attributes: { objectApiName: 'Contact', actionName: 'list' }, state: { filterName: 'AllContacts' } }. It corresponds to the pattern /lightning/o/Contact/list?filterName=AllContacts, the same shape as the Account Recent example.
Exercise
You want a "View account" link that supports opening in a new browser tab but still avoids a full page reload on a normal click. Which two mixin methods do you combine, and what does each do?
Show answer
Use GenerateUrl to get the URL string for the href, which makes the link work with middle-click and copy-link. Use Navigate in the click handler after calling event.preventDefault(), which performs the in-app page change on a normal click.