Ways to Get the Current Record ID in Lightning Web Components (LWC) document

In Salesforce development, especially with Lightning Web Components (LWC), the Record Id is one of the most fundamental pieces of data you’ll work with. It’s the unique identifier that tells Salesforce which record you’re interacting with  whether it’s an Account, Contact, Opportunity, or a custom object.

Without the record Id, your component wouldn’t know which record to query, update, or display. Think of it as the “primary key” in a database table: everything else hangs off it.

Why Record Id Is Important in LWC:

Contextual Awareness: When your LWC is placed on a record page, it needs to know which record it belongs to.

Data Operations: Apex calls, wire adapters (getRecord, getRecordUi), and navigation all rely on the record Id.

Reusability: Components that correctly handle record Ids can be reused across multiple objects and pages.

Different Ways to Get the Current Record Id in LWC

1. The Standard Property: @api recordId 

The simplest and most common way. When an LWC is placed on a record page, Salesforce automatically injects the record Id.

When you place a component on a record-specific page (like an Account or Opportunity page), the Lightning Framework identifies the ID of that record. If your component has a public property specifically named recordId, the framework automatically “injects” the value into that property. Use this when your component is directly on a record page.

import { LightningElement, api } from 'lwc';

export default class RecordIdExample extends LightningElement {
    @api recordId; // Salesforce sets this automatically
}

2. Using CurrentPageReference:

If your component is on an App Page, Utility Bar, or embedded in another context, you can wire the page reference.

import { LightningElement, wire } from 'lwc';
import { CurrentPageReference } from 'lightning/navigation';
export default class PageReferenceExample extends LightningElement {
    recordId;
    @wire(CurrentPageReference)
    getPageReference(pageRef) {
        if (pageRef?.state?.recordId) {
            this.recordId = pageRef.state.recordId;
        }
    }
}

Not every component lives on a Record Page. Sometimes, you build a Custom Tab or a page in Experience Cloud. In these cases, the component is “floating” without a direct record parent. However, the Record ID is usually hidden in the URL (the website link). We use the lightning/navigation module to “listen” to the URL and extract the ID.

Example:

Consider a custom “Dashboard” where a user clicks a button to see details for a specific Lead. The URL might look like …/my-page?c__targetId=00Q…. The standard @api recordId will be empty here, so you must parse the URL parameters manually. 

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

export default class UrlIdExtractor extends LightningElement {
    extractedId;

    @wire(CurrentPageReference)
    getStateParameters(pageRef) {
        if (pageRef && pageRef.state) {
            // Extracts 'recordId' or a custom parameter from the URL
            this.extractedId = pageRef.state.recordId || pageRef.state.c__id;
        }
    }
}

3. Passing Record Id from Parent Component

One of the most flexible ways to work with the record Id in Lightning Web Components is to pass it from a parent component down to a child. This pattern is especially useful when:

  • You have a dashboard parent component that needs to orchestrate multiple child components (Contacts list, Opportunities chart, Cases table).

You want to keep child components reusable; they don’t

<!-- parentLwc.html -->
<template>
    <lightning-card title="Account Dashboard">
        <!-- Pass the recordId down to child components -->
        <c-account-contacts record-id={recordId}></c-account-contacts>
        <c-account-opportunities record-id={recordId}></c-account-opportunities>
        <c-account-cases record-id={recordId}></c-account-cases>
    </lightning-card>
</template>

// parentLwc.js

import { LightningElement, api } from 'lwc';

export default class ParentLwc extends LightningElement {
    @api recordId; 
    // Salesforce automatically injects this when the parent is placed on a record page
}

<!– accountContacts.html –>

<template>
    <lightning-card title="Contacts">
        <template if:true={contacts.data}>
            <lightning-datatable
                key-field="Id"
                data={contacts.data}
                columns={columns}>
            </lightning-datatable>
        </template>
    </lightning-card>
</template>

// accountContacts.js

import { LightningElement, api, wire } from 'lwc';
import { getRelatedListRecords } from 'lightning/uiRelatedListApi';

export default class AccountContacts extends LightningElement {
    @api recordId; // receives from parent

    columns = [
        { label: 'Name', fieldName: 'Name' },
        { label: 'Email', fieldName: 'Email' }
    ];

    @wire(getRelatedListRecords, {
        parentRecordId: '$recordId',
        relatedListId: 'Contacts',
        fields: ['Contact.Name', 'Contact.Email']
    })
    contacts;
}
  • The parent component gets the recordId automatically when placed on an Account record page.
  • It passes that Id down to each child component via an attribute (record-id={recordId}).
  • Each child component declares @api recordId to receive it.
  • The child then uses that Id to query related records, navigate, or perform actions.

Instead of relying on Salesforce to inject the record Id (@api recordId) or wiring CurrentPageReference, you manually read the browser’s URL and parse out the Id.

Salesforce record URLs typically look like this: https://satyamparasa-dev-ed.lightning.force.com/lightning/r/Account/0015g00000ABCdE/view

Here:

  • 0015g00000ABCdE is the record Id.
  • It sits between the object name (Account) and the action (view).
import { LightningElement } from 'lwc';
export default class UrlRecordIdExample extends LightningElement {
    recordId;

    connectedCallback() {
        const url = window.location.href;
        // Split the URL by '/' and find the record Id
        const parts = url.split('/');
        // In Lightning, the record Id is usually at index 5
        this.recordId = parts[6];
        console.log('Record Id from URL:', this.recordId);
    }
}

Why It’s Not Recommended

  • Fragile: Salesforce URL structures can change (Classic vs Lightning, or future updates).
  • Context‑dependent: Works only if the component is loaded on a record page with a predictable URL.
  • No guarantees: If the component is used in an App Page, Utility Bar, or Console, the URL may not contain the record Id in the same place.
  • Best practice: Use @api recordId or CurrentPageReference instead, because Salesforce guarantees those values.

Extracting the record Id from the URL works, but it’s brittle. Use it only as a last resort. Prefer @api recordId or CurrentPageReference for reliable, future‑proof solutions.

5. NavigationMixin (When You Already Know the Id)

Suppose you have a button in your LWC that should take the user directly to an Account record page. You already have the Account Id (maybe from Apex, a wire adapter, or a parent component).

  • NavigationMixin is a Salesforce utility that lets you programmatically navigate to different pages in Lightning Experience.
  • It’s imported from lightning/navigation.
  • You use it when you already know the record Id or the target page you want to navigate to.
import { LightningElement } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';

export default class NavigateExample extends NavigationMixin(LightningElement) {
    handleNavigate() {
        this[NavigationMixin.Navigate]({
            type: 'standard__recordPage',
            attributes: {
                recordId: '0015g00000ABCdE',   // known Account Id
                objectApiName: 'Account',
                actionName: 'view'
            }
        });
    }
}
<template>
    <lightning-button label="Go to Account" onclick={handleNavigate}></lightning-button>
</template>

When the button is clicked, the user is taken directly to the Account record page.

Conclusion: 

In Salesforce Lightning Web Components, the recordId is the key to knowing which record your component is working with, and there are several ways to access it depending on context; the most reliable is the @api recordId property, which Salesforce automatically injects when the component is placed on a record page. For app pages or utility bars you can wire CurrentPageReference to read the Id from the URL state. you can also pass the Id from a parent component into a child via attributes to keep components modular and reusable, in rare cases developers parse the Id directly from the browser URL, though this is fragile and not recommended; and finally, if you already know the Id from Apex or data, you can use NavigationMixin to programmatically navigate to record pages, list views, or external URLs together these approaches ensure your LWCs remain flexible, robust, and context‑aware across different real‑world scenarios.

Satyam parasa
Satyam parasa

Satyam Parasa is a Salesforce and Mobile application developer. Passionate about learning new technologies, he is the founder of Flutterant.com, where he shares his knowledge and insights.

Articles: 69

Leave a Reply

Your email address will not be published. Required fields are marked *