Lightning Out to integrate the Salesforce real time data into external website

Scenario : Integrate Salesforce functionality into internal applications to provide real-time data and interactive features directly from Salesforce.

Salesforce Lightning Out is a powerful feature that extends the capabilities of Salesforce Lightning Components beyond the Salesforce platform, allowing them to be embedded.

To demonstrate Salesforce Lightning Out, we will create a Lightning Web Component (LWC), a Lightning Application, and display it on an external website using Salesforce Site. This process involves the following steps:

  • Create a Lightning Web Component (LWC)
  • Create Lightning App to display LWC
  • Create an Apex Controller to create data
  • Setup Salesforce Site
  • Configure the Lightning Out in an External Website html Page

Step 1: Create a Lightning Web Component (LWC) in Salesforce

  • Create Lightning Web Component and name it “accountManagement”.
  • Follow steps, if you never created lwc before.
  • To make the LWC available for Lightning Out, we need to expose the lwc by setting isExposed flag to TRUE in metadata xml file.
				
					// accountManagement lwc js 
// handleAccountCreated method : for creating the account record when requested by user.
import { LightningElement, wire, api, track } from 'lwc';
import ACCOUNT_OBJECT from "@salesforce/schema/Account";
import NAME_FIELD from "@salesforce/schema/Account.Name";
import createAccount from '@salesforce/apex/DataFactoryController.createAccount';

export default class accountManagement extends LightningElement {

  accountObject = ACCOUNT_OBJECT;
  nameField = NAME_FIELD;

  handleAccountCreate() {
    console.log('**** creating account ****');
    createAccount({ uuidVal: nameField })
      .then((result) => {
        if (result) {
          console.log('account created successfully : ', result);
        }
      })
      .catch((error) => {
        this.error = error;
      });
  }
}
				
			
				
					<!-- 
  accountManagement lwc html 
  accepting user input Account Name
-->
<template>
  <lightning-record-edit-form object-api-name={accountObject} onsuccess={handleAccountCreate}>
    <lightning-messages></lightning-messages>
    <div class="slds-grid">
      <div class="slds-col slds-size_1-of-2">
        <lightning-input-field field-name={nameField}></lightning-input-field>
      </div>
    </div>
    <lightning-button type="submit" variant="brand" label="Create Account"></lightning-button>
  </lightning-record-edit-form>
</template>
				
			
				
					<!-- 
  accountManagement lwc meta xml 
  important configues to display lwc properly.
  note - isExposed = TRUE
-->
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>59.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__Tab</target>
    </targets>
    <masterLabel>
        Account Management
    </masterLabel>
</LightningComponentBundle>
				
			

Step 2: Create an Apex Controller to Create Account Records

  • Create a new Apex class and name it as “DataFactoryController“.
				
					public without sharing class DataFactoryController {

    @AuraEnabled(cacheable=true)
    public static Account createAccount(String name){
        Account account = new Account(Name = name);
        insert account;
        return account;
    }

}
				
			

Step 3: Create Lightning App to display LWC content

  • Open Developer Console in Salesforce, and click on New -> Lightning Application, then give name as “AccountManagementApp
				
					<!-- 
application file comments
aura:dependency to embed the lwc in lightning app
note - access is global and it extends the ltng:outApp
-->
<aura:application description="Account Management App" access="GLOBAL" 
                  extends="ltng:outApp" implements="ltng:allowGuestAccess">
	<aura:dependency resource="c:accountmanagement" />
</aura:application>
				
			

Step 4: Create Salesforce Site

Create Salesforce Site to render the App. 

  • Navigate to Setup -> Search Sites, and create new Site and name it as “accountmanagement
  • This will generate new Site URL as “domainName/” + “siteName”
  • ex: https://jumpcloud–theWesternTech.sandbox.my.site.com/accountmanagement

Step 5: Configure Lightning Out in a external html page

At this point we already have our LWC, Lightning App to display LWC. Now we need to embed these components in html page. 

  • Create new html file in local machine and name it as “AccountManagement.html
				
					<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
</head>

<body>
    <h1>Account Management Application</h1>
    <script src="https://jumpcloud--theWesternTech.sandbox.my.site.com/accountmanagement/lightning/lightning.out.js">
        //this is site url
    </script>  
    <div data-lightning-out="true"></div>

    <script>
        const appName = 'c:accountmanagementapp'; //Lightning Ap
        const componentName = 'c:accountmanagement'; //LWC
        const lightningEndpoint = 'https://jumpcloud--theWesternTech.sandbox.my.site.com/accountmanagement'; //Sandbox Site URL
        const targetElement = document.querySelector("[data-lightning-out]");
        const componentAttribute = {};

        $Lightning.use(
            appName, // name of the Lightning Out app
            function () { // callback after the framework and app load
                $Lightning.createComponent(
                    componentName, // top-level component of the Lightning Out app
                    componentAttribute, // attributes to set on the component
                    targetElement, // DOM element ID where the component is inserted
                    function (cmp) { // callback after the component loads
                        console.log('The component was created.');
                    }
                );
            },
            lightningEndpoint // Experience Cloud site endpoint
        );
    </script>

</body>
</html>