Current User Id in LWC, Aura, Apex, and Visualforce

This is a simple but very useful post. This post will show how can we get the Current User Id in LWC (Lightning Web Component), Aura, Apex, and Visualforce. Let’s just get into the implementation.

Current User Id in LWC, Aura, Apex, and Visualforce
Current User Id in LWC, Aura, Apex, and Visualforce

Current User Id in LWC (Lightning Web Component)

To get the current User Id in LWC, we need to import @salesforce/user/Id scoped module which will return the current user Id.

currentUser.js

import { LightningElement } from 'lwc';
import uId from '@salesforce/user/Id';
export default class CurrentUser extends LightningElement {
    userId = uId;
}

Then we can user this userId property to display it on UI.

currentUser.html

<template>
    <lightning-card title="Current U">
        <p>Current User Id : {userId}</p>
    </lightning-card>
</template>

Current User Id in Aura Component

To get the current User Id in Lightning Aura Component, we can use Global variable $A.

currentUserAura.cmp

<aura:component implements="flexipage:availableForAllPageTypes" access="global">
    <aura:attribute name="userId" type="String" />
    <aura:handler name="init" value="{!this}" action="{!c.init}" />
    
    Current User Id : {!v.userId}
    
</aura:component>

currentUserAuraController.js

({
	init : function(component, event, helper) {
		var userId = $A.get("$SObjectType.CurrentUser.Id");
        component.set("v.userId", userId);
	}
})

Current User Id in Visualforce Page

To get the current User Id in the Visualforce page, we can use the Global variable $User.

currentUserPage.vfp

<apex:page>
    Current User Id : {!$User.Id}
</apex:page>

Current User Id in Apex Class

To get the current User Id in Apex Class, we can use getUserId() method of UserInfo System Class.

CurrentUserClass.apxc

public class CurrentUserClass {
    public CurrentUserClass(){
        String userId = UserInfo.getUserId();
        System.debug('Current User Id : ' +userId);
    }
}

This is how we can get the Current User Id in LWC (Lightning Web Component), Aura, Apex, and Visualforce Page.

If you want to check more implementations using Lightning Web Components, you can check it here.

Please Subscribe if you don’t want to miss new posts. Thanks!