Embed Salesforce LWC components in your storefront
On this page
StoreConnect storefronts use a Liquid-based theme engine, but you can also embed Salesforce Lightning Web Components (LWC) directly into your storefront pages. This lets you bring Salesforce-native UI and logic into your store without rebuilding it in Liquid or JavaScript.
This can be achieved using Salesforce Lightning Out combined with a secure, token-based authentication layer. The StoreConnect theme generates an HMAC-signed token server-side, and a wrapper LWC on the Salesforce side verifies the token before dynamically rendering your component with authenticated customer data. Depending on your setup, there are also other ways to approach this.
:::note
This article covers the online storefront. The point of sale app is a separate surface, and Lightning Out is not the way to customize it. See Lightning Out and the point of sale below.
:::
This article covers Lightning Out 1.0, which loads through lightning.out.js. Salesforce also offers a newer Lightning Out release with a different loader and authentication flow; the setup below does not apply to it.
A ready-to-deploy proof of concept project is available for download:
Download the StoreConnect Secure LWC project
How it works
The embedding process follows a secure handshake between StoreConnect and Salesforce:
-
Token generation (StoreConnect) — When a storefront page loads, the Liquid template generates a JSON payload containing the customer’s context (Customer ID, Store ID) and a timestamp. This payload is cryptographically signed using HMAC-SHA256 with a shared secret stored in Store Variables. The resulting token is embedded into the page HTML.
-
Client-side loading — The browser loads the Salesforce Lightning Out library via a singleton loader (preventing duplicate script loads when multiple components are on the same page). A wrapper LWC is initialized and receives the signed token along with the name of the component to render.
-
Server-side verification (Salesforce) — The wrapper LWC passes the token to an Apex controller. Apex retrieves the shared secret for the originating store, recalculates the HMAC signature, and verifies it matches. It also checks that the token has not expired (1-hour window with 30-second clock skew tolerance).
-
Dynamic rendering — Once verified, the wrapper dynamically instantiates the requested business component and passes the authenticated customer data down to it. The component renders inside the storefront page.
```text
StoreConnect Salesforce +——————————+ +———————————–+ | 1. Page loads | | | | 2. Liquid generates | | | | HMAC-signed token | | | | 3. Token embedded in HTML | | | | | | | | 4. Browser loads | ——> | 5. Wrapper LWC receives token | | Lightning Out library | | + component name | | | | | | | | 6. Apex validates: | | | | - Retrieve store secret | | | | - Verify HMAC signature | | | | - Check token expiry | | | | | | | <—— | 7. Render requested component | | 8. Resize and error events | <—— | with authenticated data | | via postMessage | | | +——————————+ +———————————–+ ```
Security features
- Tamper-proof — Any modification to the token (for example, changing the Customer ID) invalidates the signature and causes immediate rejection.
- Zero-trust — No secrets or API keys are ever exposed to the client browser. The token carries a signed claim about who the customer is, not a Salesforce credential, so a copied token grants nothing beyond what Apex chooses to return for that customer. The HMAC secret stays server-side in the Store Variable record and is never rendered into the page.
- Cache compatible — The stateless design (timestamp + signature) works with StoreConnect’s page caching without triggering false security errors, as long as the page is not cached for longer than the token stays valid.
- Component allowlist — Only explicitly registered components can be loaded. The wrapper uses a
COMPONENT_MAPobject as a security gate, preventing arbitrary component injection. - Constant-time comparison — Signature verification uses constant-time string comparison to prevent timing attacks.
- Token expiry — Tokens are valid for 1 hour from generation, with a 30-second clock skew tolerance for server time differences.
:::warning
Do not simplify this by having the theme fetch a Salesforce access token and pass that to the component instead. An access token says nothing about which customer is on the page, so Apex can no longer tell one shopper from another, and the token itself is a credential for the whole org rather than a claim about one person. Signing a claim is what lets the component trust who it is rendering for. Where a template genuinely needs to call Salesforce for data rather than render a Salesforce interface, keep the credential on the server and use the api tag, as described in Bring external data into POS.
:::
Alternative approaches
Depending on what you are building, you may not need LWC embedding at all. StoreConnect provides several ways to add custom functionality to your storefront:
- Liquid templates with custom JavaScript — Full control over markup and scripting using the theme engine. See Adding custom JavaScript, CSS and head content.
- Content blocks with raw HTML/JS — Use the “No added styling” content block template to insert custom HTML and JavaScript. See Content block templates.
- Server-side API proxy — Use Liquid’s api tag and Store Variables to call external APIs server-side without exposing credentials. This is useful for fetching and displaying data from third-party services, and it works just as well against your own Salesforce Apex REST endpoints.
If all you need is live Salesforce data on the page, rather than a Salesforce user interface, reach for the API proxy first. An Apex REST endpoint called through the api tag is considerably less to set up and keeps every credential on the server. Choose LWC embedding when you need the component itself: an existing Salesforce interface you want to reuse, or the Lightning component ecosystem on your storefront.
Lightning Out and the point of sale
Lightning Out embeds a Lightning Web Component in a page outside Salesforce, and the pattern above does that for a storefront page. The same technique can be pointed at a POS screen, but it is not the right tool there, for three reasons.
- It depends on a Salesforce session. The embedded component authenticates against Salesforce, so its behavior is tied to Salesforce authentication settings that change independently of your store. A register is unattended equipment running a long shift, which is the worst place for a sign-in that can start failing without a change on your side.
- It forces a round trip before the screen updates. Anything the component writes goes to Salesforce, and the register only reflects it once that record has synced back down to the device. Staff see a delay between acting and the screen agreeing with them.
- The authentication above cannot be rebuilt in POS. A POS View renders its Liquid on the
device rather than on the server, and that smaller Liquid feature set has no
hmacfilter and noapitag, so a view cannot sign a token or verify one. Anything built this way at a register has to authenticate some other way, and the straightforward options all end up putting a credential on the device.
Use a POS View instead. A view holds your own Liquid, HTML, CSS, and JavaScript, renders directly in POS, and can do the same work without either problem:
- Attach it to a layout, a layout field, or a grid card. See POS layouts.
- Call Salesforce, including your own Apex REST services, and call other systems through a relay page that keeps credentials off the device. See Bring external data into POS.
- Drive POS itself from the view’s JavaScript, to add an item to the cart, start a checkout, process a return, or print. See scAction and the POS actions reference.
Before you start
- A Salesforce org with the StoreConnect managed package installed.
- Salesforce CLI (
sf) installed locally. - A public Salesforce site to serve the Lightning Out endpoint. An Experience Cloud site is the usual choice, and a Salesforce Site works equally well.
- Edit access to your store’s theme templates. See Theme pages.
- Permission to create Store Variables on the Store record.
What is in the project
The downloadable project contains everything needed to get LWC embedding working:
| File | Purpose |
|---|---|
templates/blocks/lwc.liquid |
Liquid content block template for your StoreConnect theme. Handles token generation and Lightning Out initialization. |
force-app/main/default/classes/StoreConnectAuthHandler.cls |
Apex class that validates HMAC-signed tokens. Retrieves the shared secret from Store Variables, verifies the signature, and checks token expiry. |
force-app/main/default/classes/StoreConnectAuthHandlerTest.cls |
Apex test class covering valid tokens, expired tokens, tampered signatures, and invalid store IDs. |
force-app/main/default/lwc/storeConnectWrapper/ |
Wrapper LWC that authenticates the token via Apex, then dynamically renders the requested component. Uses a component allowlist for security. |
force-app/main/default/aura/StoreConnectLWCOut/ |
Lightning Out Aura application. This is a Salesforce requirement for serving LWC components externally, and it is also where guest access is declared. |
README.md |
Full setup instructions, architecture overview, and development commands. |
Set up Salesforce
Step 1: Deploy the Apex and LWC components
From the project directory, deploy to your Salesforce org:
```bash
sf project deploy start –source-dir force-app ```
This deploys:
- The StoreConnectAuthHandler Apex class and its test class
- The storeConnectWrapper LWC
- The StoreConnectLWCOut Aura application
The deploy command reports Deploy Succeeded and the three components appear in Setup.
:::warning
Signed-out storefront visitors can only load the components if the Lightning Out application allows guest access. The application declares this itself, so check that its .app file implements ltng:allowGuestAccess alongside ltng:outApp. Without it, every visitor who is not logged in to Salesforce sees an empty container, even though the token validates correctly. This matters whenever your token’s sub claim can be guest.
:::
Step 2: Set up the Lightning Out site
The Lightning Out endpoint is served by a public Salesforce site. If you do not already have one, create an Experience Cloud site in Salesforce Setup under Digital Experiences > All Sites. A Salesforce Site created under Sites works just as well, and serves the same endpoint from a salesforce-sites.com domain.
Publish the site, then record its base URL and the Lightning Out script URL beneath it. You need both in the next section.
- Lightning Out script URL — the site’s base URL followed by
/lightning/lightning.out.js - Site URL — the site’s base URL
For an Experience Cloud site these look like https://example-domain.my.site.com/lightning/lightning.out.js and https://example-domain.my.site.com, substituting your own domain.
Set up StoreConnect
Step 1: Configure Store Variables
- Open the Store record and go to the Store Variables related list.
- Create three store variables, one per row below. Set Available in Liquid to
trueon all three, or the theme cannot read them.
| Key | Description | Example value |
|---|---|---|
SC_HMAC_Secret |
The HMAC secret the theme signs with and Apex verifies against | A strong random string (at least 32 characters) |
SF_My_Salesforce |
The Lightning Out script URL you recorded above | https://example-domain.my.site.com/lightning/lightning.out.js |
SF_My_Experience |
The site base URL you recorded above | https://example-domain.my.site.com |
Store Variables are Salesforce records (s_c__Store_Variable__c), so this is the only place the secret is stored. There is no second copy to keep in step, and Apex reads the same record the theme signs with. Repeat these three variables for each store that embeds LWC components.
:::warning
Do not name the secret with a pos. prefix. Store Variables whose key begins with pos. are synchronized to every POS register and stored unencrypted in the register’s local database, where any staff member can read them. Keys that do not start with pos. stay on the server. SC_HMAC_Secret is safe; pos.hmac_secret would expose the secret on every device.
:::
:::note Generate the secret as a strong random string of at least 32 characters, and treat it like any other credential. Anyone holding it can mint tokens that Apex will accept. :::
Step 2: Add the Liquid template to your theme
Copy templates/blocks/lwc.liquid from the project into your StoreConnect theme’s templates directory at templates/blocks/lwc.liquid.
This creates a new content block template called lwc that you can use to embed components.
Step 3: Create a content block template option
In Salesforce, add lwc as a new picklist value to the Content_Block__c.Template__c field. This makes the template available when creating content blocks.
Step 4: Embed a component
- Go to the Content Blocks list and select New (
s_c__Content_Block__c). - Set the Template to
lwc. - Set the Content field to the name of the component you want to render, for example
contactSupportForm. - Save the record and add the block to a page.
The Liquid template reads the component name from the content block, generates a signed token, and handles the Lightning Out initialization automatically.
Load the page on your storefront. The component renders in place of the content block, and the
browser console shows no SC_AUTH_ERROR messages.
Register custom components
The wrapper uses a component allowlist for security. Only components explicitly imported and registered in the COMPONENT_MAP can be loaded.
To add a new embeddable component:
- Create your LWC under
force-app/main/default/lwc/in your Salesforce org. -
Import it in
storeConnectWrapper.jsand add it to theCOMPONENT_MAP:```javascript
import MyComponent from ‘c/myComponent’;
const COMPONENT_MAP = { // …existing components ‘myComponent’: MyComponent, }; ```
-
Read
authDatain your component. It is a property containing all token claims:```javascript
// In your custom component import { LightningElement, api } from ‘lwc’;
export default class MyComponent extends LightningElement { @api authData; // Contains: isValid, customerId, and any custom claims } ```
- Deploy the updated wrapper and your new component to your Salesforce org.
- Reference the component name in a StoreConnect content block using the
lwctemplate.
The component name is now an accepted value in the Content field of any lwc content block.
:::tip You can embed multiple LWC components on the same page. Each content block gets its own container, token, and event scope. :::
Token structure
The token generated by the Liquid template follows this format:
```text
{storeId}|v1.{base64-encoded-payload}.{hex-hmac-signature} ```
The payload contains standard claims:
| Claim | Description |
|---|---|
aud |
Store domain (audience) |
exp |
Expiry timestamp (1 hour from generation) |
iat |
Issued-at timestamp |
jti |
Nonce (store + customer + time + block ID for uniqueness) |
sub |
Customer ID, or guest for unauthenticated visitors |
Auto-resizing
The wrapper LWC uses a ResizeObserver to monitor the rendered component’s height and sends postMessage events back to the storefront. The Liquid template listens for these events and adjusts the container height automatically. This means embedded components resize smoothly without scrollbars or fixed heights.
Error events (SC_AUTH_ERROR) are also sent via postMessage and logged to the browser console, scoped to the specific component name.
Troubleshooting
Component does not render
- Verify the component name in the content block exactly matches a key in the
COMPONENT_MAPinstoreConnectWrapper.js - Check the browser console for authentication errors
- Confirm the site is published and accessible
- If the container is empty only for signed-out visitors, and only while you are logged out of Salesforce yourself, the Lightning Out application is missing
ltng:allowGuestAccess
Authentication errors
- Confirm the Store Variable holding
SC_HMAC_Secretis on the same Store record the page is served from, and that Available in Liquid istrue - Check that the
Store_Id__con that record matches the Store ID in the token - If you see “Token expired” errors, verify that your server clocks are reasonably in sync (the system allows 30 seconds of skew)
- If tokens expire on some page loads but not others, check whether the page is cached for longer than the token’s one-hour lifetime. A token baked into a cached fragment ages with the cache, not with the request. Shorten the cache duration for that page, or exclude the block from caching
Lightning Out script fails to load
- Verify the
SF_My_SalesforceStore Variable contains the correct URL ending in/lightning/lightning.out.js - Confirm the site is published and the URL in
SF_My_Experienceis correct - Check for Content Security Policy (CSP) errors in the browser console; you may need to add your Salesforce domain to your store’s CSP trusted sites
Multiple components on the same page
Each content block generates its own unique container ID and token. The postMessage events include the component name so resize and error events are scoped correctly. If components are interfering with each other, check that each content block has a unique identifier.
Was this article helpful?
Thanks for your feedback! It helps us improve our docs.