When we build Lightning Web Components, getting the recordId is very important. We need it to fetch data, call Apex, show forms, or know which record the user is viewing.
For example, imagine you add a Lightning Web Component to the Account record page. When a user opens any Account, the LWC should automatically show all Opportunities related to that Account.
To show the correct data, the component must know which Account is currently open. To do this, the component must first get the Record ID.
In Salesforce, a record ID is a unique identifier for a Salesforce object. To get or fetch the record ID in a Lightning Web Component, we need to add the component to the Lightning record page of that specific object.
In this article, we will learn different ways to get record ID in LWC in Salesforce using practical examples.
Get Record ID in LWC in Salesforce
To get the recordId of the current record in the Lightning Web Component, we will use the @api decorator, which exposes the record ID for public access.
Follow the steps below to create a Lightning Web Component that displays the current object’s record ID. Since this component displays the record ID, it will be exposed and deployed to the lightning__RecordPage target.
- Create an LWC component and enter the code below in the HTML to define the UI of the component.
<template>
<lightning-card title="Get Record ID ">
<div class="slds-p-around_medium">
<p>Current Record ID: {recordId}</p>
</div>
</lightning-card>
</template>
- After this, enter the code below in the JS file to define the logic of fetching the current record ID.
import { LightningElement, api } from 'lwc';
export default class GetRecordIdExample extends LightningElement {
@api recordId;
connectedCallback() {
console.log('Record ID:', this.recordId);
}
}
In the above code, we have set recordId as public with the @api decorator, allowing it to receive a record ID from its parent or context, such as a Salesforce record page.
When the component is added to the Lightning record page, the connectedCallback() method runs and displays the record ID in the Lightning web component.
- Enter the code below in the meta.xml file to expose the lightning web component to the record page.
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>63.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__RecordPage</target>
</targets>
</LightningComponentBundle>
- After this, navigate to any object record pages and deploy the LWC component. In this example, I will deploy the LWC component on the Opportunity object record page.
- On the record page, click on the settings icon and select Edit Page.
- In the Lightning App Builder, drag and drop the LWC component into the template region, then save the changes.

Now, in the L