Sub topic 10
Reading the current page with CurrentPageReference
This chapter assumes you can call NavigationMixin.Navigate with a page reference and that you know how @wire binds a function or property to a data source. Earlier chapters covered Navigate, GenerateUrl, and the state property. Here you read the same kind of object back.
What CurrentPageReference returns
CurrentPageReference is a wire adapter exported from lightning/navigation. It gives your component the page reference of the page it is on. The object has the same shape you pass to Navigate:
type: the page type, such asstandard__recordPageorstandard__navItemPage.attributes: the values that identify the page, such asrecordIdorapiName.state: optional key-value pairs, usually URL query parameters.
The adapter describes the page that hosts your component, not the component itself. A component on a record page sees the record page reference. The same component on an app page sees the app page reference.
The adapter is reactive. When the user moves to another page, or the state changes on the same page, the adapter emits a new value and your wire function or property updates.
import { LightningElement, wire } from 'lwc';
import { CurrentPageReference } from 'lightning/navigation';
export default class PageInspector extends LightningElement {
pageRef;
@wire(CurrentPageReference)
setPageRef(pageRef) {
this.pageRef = pageRef;
}
get pageType() {
return this.pageRef ? this.pageRef.type : '';
}
get recordId() {
return this.pageRef ? this.pageRef.attributes.recordId : undefined;
}
}You can also wire to a property, @wire(CurrentPageReference) pageRef;. A function is the better choice when you need to run logic on each change, such as reading a parameter or loading data.
Reading state
The state object carries values that are not part of the page identity. On a Lightning Experience page, a URL such as /lightning/n/Orders?c__status=open produces this page reference:
{
type: 'standard__navItemPage',
attributes: { apiName: 'Orders' },
state: { c__status: 'open' }
}Three rules matter here.
- Custom keys must start with
c__. Lightning Experience drops other custom keys from the URL, so they never reach your component. - Every value in
stateis a string. Convert numbers and booleans yourself. statecan be missing or empty. Guard against it before reading a key.
The object you receive is read-only. Do not assign pageRef.state.c__status = 'closed' and expect the URL to change. To change state, navigate to a new page reference.
Changing state with Navigate
The usual pattern is to read the state from the wire and write it with Navigate. The page keeps the same type and attributes and gets a new state. The second argument of Navigate is a boolean named replace. When it is true, the new location replaces the current browser history entry, so the Back button does not step through every filter change.
This component filters a list by a c__status query parameter. It also treats a missing parameter as a default.
<template>
<lightning-card title="Orders">
<p class="slds-p-horizontal_small">Showing: {status}</p>
<div class="slds-p-around_small">
<lightning-button label="Open" onclick={showOpen}></lightning-button>
<lightning-button label="Closed" onclick={showClosed}></lightning-button>
</div>
</lightning-card>
</template>import { LightningElement, wire } from 'lwc';
import { CurrentPageReference, NavigationMixin } from 'lightning/navigation';
export default class OrderStatusFilter extends NavigationMixin(LightningElement) {
pageRef;
status = 'all';
@wire(CurrentPageReference)
handlePageRef(pageRef) {
this.pageRef = pageRef;
const state = pageRef && pageRef.state ? pageRef.state : {};
this.status = state.c__status || 'all';
}
showOpen() {
this.setStatus('open');
}
showClosed() {
this.setStatus('closed');
}
setStatus(value) {
if (!this.pageRef) {
return;
}
this[NavigationMixin.Navigate](
{
type: this.pageRef.type,
attributes: this.pageRef.attributes,
state: { ...this.pageRef.state, c__status: value }
},
true
);
}
}The spread ...this.pageRef.state keeps any other parameters already in the URL. If you leave it out, you wipe them.
To place this component on a custom tab, expose it in the metadata file:
<?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__Tab</target>
</targets>
</LightningComponentBundle>The data flow
Because the state lives in the URL, the page reference is the single source of truth. Your component does not keep its own copy of the filter and try to stay in sync. It asks the router to change the URL, and the wire delivers the result.
This also means a user who opens a bookmarked link, or a link made with GenerateUrl, gets the same view as someone who clicked the buttons. The wire function runs once with the state from the URL.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `state` is empty even though the URL has a parameter | The key has no `c__` prefix | Rename the parameter to `c__yourKey` |
| Component works in one app and not in another | The page type differs, so `attributes` has different keys | Check `type` before reading from `attributes` |
| `TypeError` reading `pageRef.state.c__x` | `pageRef` or `state` is `undefined` on first call | Guard both, as in `handlePageRef` above |
| Assigning to `pageRef.state` has no effect or throws | The object is read-only | Call `Navigate` with a new `state` |
| Back button steps through every filter change | `Navigate` was called without `replace` | Pass `true` as the second argument |
| A numeric filter compares wrong | State values are strings | Convert with `Number()` or compare strings |
Gotchas
The adapter works inside Lightning Experience, Experience Cloud sites, and the Salesforce mobile app. It does not provide a useful value in Lightning Out or in a component previewed on its own. Test page-dependent logic on a deployed page, not only in a local preview.
Do not use the adapter to detect where a component was embedded. A component inside a modal or a child of another component still sees the page behind it. If you need to know the parent's context, pass it down with @api properties.
Avoid heavy work in the wire function. It runs on every navigation and state change that reaches the component. Compare the new value with the old one before you call Apex or a data adapter.
Summary of the pattern
- Import
CurrentPageReferenceand, if you will write state,NavigationMixin. - Wire a function and store the page reference.
- Read parameters from
pageRef.statewith guards and defaults. - Change state by calling
Navigatewith the sametypeandattributesand a newstate. - Pass
trueas the second argument when the change should not add a history entry.
Exercise
A component reads this.pageRef.state.c__page and gets undefined on a page whose URL ends in ?page=2. The component then calls Navigate with state: { c__page: 3 } to move to the next page. Name the two problems and give the fix for each.
Show answer
First, the URL parameter has no c__ prefix, so Lightning Experience does not pass it into state. Rename it to c__page in the links that point to the page. Second, state values are strings, so c__page is read as '2' and 3 should be passed as '3'. Convert on read with Number(state.c__page) and write with String(next). It is also safer to spread the existing state, { ...this.pageRef.state, c__page: String(next) }, so other parameters are kept.
Exercise
Why does OrderStatusFilter set this.status inside the wire function instead of inside setStatus, right after calling Navigate?
Show answer
The URL is the source of truth. If setStatus also set status directly, the component could show a value that differs from the URL, for example when navigation is blocked or when the user opens a bookmarked link. Setting it in the wire function means one code path handles clicks, bookmarks, reloads, and Back and Forward.