Sub topic 8
Generating URLs for links with GenerateUrl
NavigationMixin.Navigate moves the user to a page right now. NavigationMixin.GenerateUrl instead gives you the URL of a page, so you can put it in a link. This chapter covers when to choose each one, how the Promise works, and the mistakes that make generated links fail.
This chapter assumes you can apply NavigationMixin to a component and that you know what a PageReference object looks like. It also assumes you are comfortable with Promises and async/await.
Why generate a URL instead of navigating
A button that calls Navigate works, but it is not a real link. The browser does not know where the button leads. Users cannot right-click it, copy the address, or open it in a new tab with Ctrl-click or Cmd-click. Screen readers announce a button, not a link.
An anchor element (<a>) with an href fixes all of this. The problem is that the correct href depends on the org, the app, and whether the code runs in Lightning Experience, the mobile app, or an Experience Cloud site. You should not build that string by hand. GenerateUrl takes the same PageReference you would pass to Navigate and returns the correct URL for the current context.
| Need | Use |
|---|---|
| Move the user after an action, such as a save | `Navigate` |
| A link the user can copy, bookmark, or open in a new tab | `GenerateUrl` |
| A link in a toast message | `GenerateUrl`, then pass the result in `messageData` |
How GenerateUrl works
You call it the same way as Navigate, through the mixin's symbol key. It returns a Promise that resolves to a string.
import { LightningElement, api } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';
export default class RecordLink extends NavigationMixin(LightningElement) {
@api recordId;
url;
connectedCallback() {
this[NavigationMixin.GenerateUrl]({
type: 'standard__recordPage',
attributes: {
recordId: this.recordId,
actionName: 'view'
}
}).then((url) => {
this.url = url;
});
}
}The matching template binds url to the anchor:
<template>
<a href={url}>Open record</a>
</template>The Promise resolves some time after the component connects. On the first render url is undefined, so the anchor has no href. When the Promise resolves and assigns this.url, the component re-renders and the link appears. This works because class fields are reactive in LWC. If the link must never appear without a target, wrap it in lwc:if={url}.
Use async/await and handle the click
The same component reads more clearly with async/await. The next version also keeps normal browser behavior for modified clicks. A plain left click goes through Navigate, so the page changes inside Lightning without a full reload. A Ctrl-click or Cmd-click falls through to the browser, which opens the href in a new tab.
import { LightningElement, api } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';
export default class AccountLink extends NavigationMixin(LightningElement) {
@api recordId;
url;
get pageReference() {
return {
type: 'standard__recordPage',
attributes: {
recordId: this.recordId,
objectApiName: 'Account',
actionName: 'view'
}
};
}
async connectedCallback() {
this.url = await this[NavigationMixin.GenerateUrl](this.pageReference);
}
handleClick(event) {
if (event.ctrlKey || event.metaKey || event.shiftKey) {
return;
}
event.preventDefault();
this[NavigationMixin.Navigate](this.pageReference);
}
}<template>
<a href={url} onclick={handleClick}>Open account</a>
</template>Sharing one pageReference getter keeps the href and the click behavior pointing at the same page.
Generating many links
A list needs one call per row. Each call returns its own Promise, so use Promise.all and set the result once.
import { LightningElement, api } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';
export default class ContactLinks extends NavigationMixin(LightningElement) {
@api contacts = [];
rows = [];
async connectedCallback() {
this.rows = await Promise.all(
this.contacts.map(async (contact) => ({
id: contact.Id,
name: contact.Name,
url: await this[NavigationMixin.GenerateUrl]({
type: 'standard__recordPage',
attributes: {
recordId: contact.Id,
objectApiName: 'Contact',
actionName: 'view'
}
})
}))
);
}
}<template>
<ul>
<template for:each={rows} for:item="row">
<li key={row.id}>
<a href={row.url}>{row.name}</a>
</li>
</template>
</ul>
</template>Assigning rows once avoids a re-render for every link.
Using a generated URL in a toast
The toast chapter showed that messageData can hold an object with url and label. You can fill that url with a generated value. This keeps the toast link correct in every context, instead of relying on a hand-built /lightning/r/... path.
import { LightningElement } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
export default class CreatedToast extends NavigationMixin(LightningElement) {
async showCreated(recordId, name) {
const url = await this[NavigationMixin.GenerateUrl]({
type: 'standard__recordPage',
attributes: { recordId, actionName: 'view' }
});
this.dispatchEvent(
new ShowToastEvent({
title: 'Record created',
message: '{0} was created. {1}',
messageData: [name, { url, label: 'Open it' }],
variant: 'success',
mode: 'sticky'
})
);
}
}Common errors
- Using the URL before it exists. Code such as
window.open(this.url)right afterconnectedCallbackstarts runs whileurlis stillundefined. Wait for the Promise, or generate the URL inside the handler withawait. - Forgetting the mixin.
this[NavigationMixin.GenerateUrl]is undefined unless the class extendsNavigationMixin(LightningElement). The error is a TypeError saying it is not a function. - A stale link.
connectedCallbackruns once. IfrecordIdchanges later, the link keeps pointing at the old record. Regenerate the URL from a setter on the@apiproperty, or from the code that changes the value. - Setting
hrefand also callingNavigatewithoutpreventDefault. The browser then follows thehrefand does a full page load as well. - Hardcoding paths. A string like
/lightning/r/Account/001.../viewbreaks in Experience Cloud sites and some app contexts. Generated URLs do not. - Invalid PageReference. If a required attribute is missing, such as
recordIdfor a record page, the Promise can reject or produce a useless URL. Add a.catchor atry/catcharoundawaitwhen the input comes from user data.
Exercise
A component calls this[NavigationMixin.GenerateUrl](pageRef) in connectedCallback and assigns the result to this.url, but the template shows <a href={url}> with no href for a moment and then it appears. A teammate suggests the link is broken. Explain what is happening, and name one change that would stop the empty-link flash.
Show answer
GenerateUrl returns a Promise, so url is undefined on the first render and the anchor has no href. When the Promise resolves and this.url is assigned, the component re-renders with the correct href. This is normal. To avoid the flash, wrap the anchor in lwc:if={url} so it renders only after the URL is available.
Exercise
You build a link with <a href={url} onclick={handleClick}> where handleClick calls this[NavigationMixin.Navigate](pageRef). Clicking works, but the browser also reloads the whole page. What is missing, and which keys should you check so Ctrl-click can still open a new tab?
Show answer
handleClick needs event.preventDefault() before calling Navigate, otherwise the browser also follows the href. To keep new-tab behavior, return early without calling preventDefault when event.ctrlKey, event.metaKey, or event.shiftKey is true.