Get Session ID in Lightning Components

Using Visualforce to securely retrieve session IDs for API calls

Retrieve Session ID for API Calls in Lightning Components

In Salesforce Lightning, retrieving the Session ID within an LWC or Aura Component isn't straightforward. Here's a secure solution using Visualforce.

The Problem

UserInfo.getSessionId() returns null in Lightning Context, blocking these scenarios:

// Returns null in Lightning
String sessionId = UserInfo.getSessionId();

The Solution: Visualforce Page in Iframe

Visualforce pages run in Classic context, allowing access to {!$Api.Session_ID}.

Step-by-Step Implementation

  1. Create a Visualforce Page
  2. Create an Apex utility class
  3. Call from your Lightning Component

1. Visualforce Page Code

<!-- SessionIdVF.page -->
<apex:page>
    Start_Of_Session_Id{!$Api.Session_ID}End_Of_Session_Id
</apex:page>

2. Apex Utility Class

// FetchSessionId.cls
public class FetchSessionId {
    
    public static String apiEnabledSessionId() {
        PageReference sessionPage = Page.SessionIdVF;
        String vfContent = sessionPage.getContent().toString();
        Integer startIndex = vfContent.indexOf('Start_Of_Session_Id') + 'Start_Of_Session_Id'.length();
        Integer endIndex = vfContent.indexOf('End_Of_Session_Id');
        
        return vfContent.substring(startIndex, endIndex);
    }
}

3. Lightning Component Usage

// In your Aura/LWC controller
getSessionId() {
    return new Promise((resolve, reject) => {
        const sessionId = FetchSessionId.apiEnabledSessionId();
        if(sessionId) {
            resolve(sessionId);
        } else {
            reject('Failed to get session ID');
        }
    });
}

Security Considerations

Alternative Approach

For pure LWC solutions, consider using: