[SalesForce] How to pass URL parameters to a Lightning App page, to load LWC in context of a record

I want to make a standalone salesforce page that loads data specific to a current member. I tried making an App page, however when I load /lightning/n/MyAppPage?recordId=something it redirects to /lightning/n/MyAppPage and drops the URL param.

Essentially what I want to do is make a standalone LWC in a standalone tab that loads data specific to an Account. I want to link out to this page from the Account view page and pass the account to my standalone LWC page as some sort of context. How can I link to such a page? I can't use the record type (Account's) view Flexipage as that has its own layout I can't overwrite for the current logged in user.

Best Answer

There is native support for query parameters in LWC. To persist, their names need to have namespace added as a prefix. Default namespace is c__.

In this example: /lightning/n/MyAppPage?recordId=something, recordId will be auto-stripped.

However, in this example: /lightning/n/MyAppPage?c__recordId=something, c__recordId will persist.

To read query params you can leverage CurrentPageReference wire, which receives object with a state attribute, which contains all the query params. The wire auto-executes, when detects any change in URL.

import { LightningElement, track, wire } from 'lwc';
import { CurrentPageReference, NavigationMixin } from 'lightning/navigation';

export default class AccountParameters extends NavigationMixin(LightningElement) {

    @track currentPageReference;
    @wire(CurrentPageReference)
    setCurrentPageReference(currentPageReference) {
        this.currentPageReference = currentPageReference;
    }

    get recordId() {
        return this.currentPageReference?.state?.c__recordId;
    }

    get objectType() {
        return this.currentPageReference?.state?.c__objectType;
    }

    get countParam() {
        return this.currentPageReference?.state?.c__randomCountParam;
    }

    // Navigates to app page on button click
    handleNavigate() {
        this[NavigationMixin.Navigate]({
            type: 'standard__navItemPage',
            attributes: {
                apiName: 'AccountsAppPageName',
            },
            state: {
                c__recordId: '001B000001KGVlCIAX',
                c__objectType: 'Account',
                c__randomCountParam: 3
            }
        });
    }
}

Related links: