Lightning Web Component

How to Get Record Id in LWC in a Simple Step

Getting the Record Id in LWC is crucial for accessing, manipulating, and displaying data specific to a record, ensuring the correct behavior of components, and facilitating data exchange between components and record pages.

Getting the Record ID in LWC

Getting the Record Id using api decorator

This method is typically used to retrieve the recordId in a Lightning Web Component embedded on a Lightning Page. It retrieves the recordId of the current record that the user is viewing.

It's as simple as declare the property @api and then the keyword recordId

import { LightningElement, api } from "lwc";

export default class getRecordId extends LightningElement {
    @api recordId;

}

I recommend you to use the method above, but if for some reason doesn't work for you here is another similar way to get the recordId that you could also use.

import { LightningElement, api } from "lwc";

export default class getRecordId extends LightningElement {
    _recordId;
    @api set recordId(value) {
        this._recordId = value;
    }
    get recordId() {
        return this._recordId;
    }

}

Getting the Record Id using CurrentPageReference and wire decorator

Using the CurrentPageReference could be helpful to get the recordId from the page URL. This is the appropriate method if you want to get the record id on a Quick Action.

Also, for this method you must import the wire property to get the data from the CurrentPageReference.

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

export default class getRecordId extends LightningElement {
    @wire(CurrentPageReference)
    currentPageReference;
    recordId;

    connectedCallback() {
        this.recordId = this.currentPageReference.attributes.recordId;
    }
}

Getting the Record Id from the URL

I recommend you use one of the above methods before trying this one since this is more custom than the others.

If the recordId is present in the URL, you can retrieve it using Javascript's window property and then the split() method to grab the recordId.

import { LightningElement } from "lwc";

export default class getRecordId extends LightningElement {
    recordId;

    connectedCallback(){
        const url = window.location.href;
        this.recordId = url.split('/r/')[1].split('/')[1];
    }
}
Getting the Record ID in LWC and showing it on a lightning-card