Sub topic 12
Using static resources and custom labels
Static resources hold the files a site component needs, such as images, CSS, and third-party JavaScript. Custom labels hold text that admins and translators can change without a code deployment. This chapter assumes you can build a basic Lightning web component, expose it to Experience Builder, and deploy with Salesforce CLI. It also assumes you know that guest users have restricted access. Earlier chapters covered those topics.
Why site components need both
Hard-coded strings and bundled images cause trouble on sites. Sites are often multilingual and branded per audience. Guest visitors also have fewer permissions than internal users. Static resources and custom labels address both problems:
| Need | Mechanism | Import path |
|---|---|---|
| Image, CSS file, or JS library | Static resource | `@salesforce/resourceUrl/<name>` |
| Translatable text | Custom label | `@salesforce/label/c.<name>` |
| Image managed by content admins | Content asset file | `@salesforce/contentAssetUrl/<name>` |
Content assets are a third option. Admins upload them in Salesforce Files and can swap them without a developer. This chapter focuses on the first two rows.
Static resources
A static resource is a file or a zip archive stored in the org. A component imports the resource's URL as a default import. The import name is the resource's API name.
import SITE_ASSETS from '@salesforce/resourceUrl/siteAssets';For a single-file resource, the imported value is the file's URL. For a zip archive, the value is the URL of the archive root. You append the path of a file inside the zip:
const logoUrl = `${SITE_ASSETS}/images/logo.png`;The resource metadata
In a Salesforce DX project, a static resource lives in force-app/main/default/staticresources. A zipped resource is usually kept as an unzipped folder next to a meta file. The CLI zips it on deploy.
<?xml version="1.0" encoding="UTF-8"?>
<StaticResource xmlns="http://soap.sforce.com/2006/04/metadata">
<cacheControl>Public</cacheControl>
<contentType>application/zip</contentType>
<description>Logo and banner stylesheet for the support site</description>
</StaticResource>Save it as siteAssets.resource-meta.xml beside a folder named siteAssets. For a single file, you instead place the file itself, such as siteAssets.png, plus the meta file. In that case set contentType to match the file, for example image/png.
Cache control and guest users
cacheControl is the setting most likely to break a site. It has two values:
Privatekeeps the resource out of shared caches. A guest user cannot reliably retrieve it. Images and styles may fail to load for unauthenticated visitors.Publiclets the resource be cached by the browser and intermediaries. Use this for anything a guest must see.
Never put sensitive content in a Public resource. Anyone with the URL can fetch it.
Loading CSS and JavaScript
Images need only a URL. CSS and JavaScript files must be loaded through lightning/platformResourceLoader. Both loadStyle and loadScript return promises.
import { LightningElement } from 'lwc';
import { loadStyle } from 'lightning/platformResourceLoader';
import SITE_ASSETS from '@salesforce/resourceUrl/siteAssets';
import WELCOME from '@salesforce/label/c.Site_Welcome';
import LOGIN_PROMPT from '@salesforce/label/c.Site_LoginPrompt';
import isGuest from '@salesforce/user/isGuest';
export default class BrandBanner extends LightningElement {
logoUrl = `${SITE_ASSETS}/images/logo.png`;
isGuest = isGuest;
error;
labels = {
welcome: WELCOME,
loginPrompt: LOGIN_PROMPT
};
connectedCallback() {
loadStyle(this, `${SITE_ASSETS}/css/banner.css`).catch((e) => {
this.error = e;
console.error('Banner stylesheet failed to load', e);
});
}
}The matching template uses the URL and the labels:
<template>
<div class="banner">
<img src={logoUrl} alt={labels.welcome} />
<h1>{labels.welcome}</h1>
<template lwc:if={isGuest}>
<p>{labels.loginPrompt}</p>
</template>
</div>
</template>Two details matter here:
loadStyletakesthisas its first argument. The platform uses it to track which component requested the file. Calling it again for the same URL does not load the file twice.- A stylesheet loaded this way applies to the page, not just to your component's shadow tree. Namespace your class names, such as
.banner, so you don't restyle other components. The chapter on styling covers branding tokens that avoid this problem.
Behavior in Aura and LWR sites
Both runtimes support @salesforce/resourceUrl. Third-party libraries are where they differ. In sites that use Lightning Web Security, a library that expects a global window or modifies built-in objects may fail or behave differently. Test any loaded library in the site itself, not only in a scratch org preview of Lightning Experience. A library that works in an internal app can break in a site.
Custom labels
A custom label is a named text value stored in the org. Each label can have translations. Components import a label as a string:
import WELCOME from '@salesforce/label/c.Site_Welcome';c is the default namespace. If the label comes from a managed package, replace c with the package namespace.
Defining labels in source
Labels deploy as CustomLabels metadata. This file defines the two labels used above:
<?xml version="1.0" encoding="UTF-8"?>
<CustomLabels xmlns="http://soap.sforce.com/2006/04/metadata">
<labels>
<fullName>Site_Welcome</fullName>
<language>en_US</language>
<protected>false</protected>
<shortDescription>Welcome heading for the support site</shortDescription>
<value>Welcome to Support</value>
</labels>
<labels>
<fullName>Site_LoginPrompt</fullName>
<language>en_US</language>
<protected>false</protected>
<shortDescription>Prompt shown to guests</shortDescription>
<value>Log in to see your cases.</value>
</labels>
</CustomLabels>Save it as force-app/main/default/labels/CustomLabels.labels-meta.xml. Labels are not a good fit for large blocks of content. A label value has a limit of 1,000 characters. Use a rich text field or CMS content for long text.
Translation
Translations come from the Translation Workbench. When the visitor selects a language on a multilingual site, the platform returns the matching translation of each label. If no translation exists for that language, the label falls back to the org's default language value. The component code does not change.
You can't build a label name from a variable at runtime. This does not work:
// Not supported: the import path must be a literal string.
import label from `@salesforce/label/c.${name}`;Each label needs its own static import. For a long list, import each label and gather them in an object, as BrandBanner does.
Labels and guest users
Guest users can read custom labels. You don't need to grant access to them. This is a difference from Apex classes and objects, which need explicit access. Because guests can read every label, don't store anything private in a label. A label is not a place for API keys or internal URLs.
How the imports resolve
The imports are resolved at build time by the platform. The component never asks for a file path or a label name at runtime.
Common errors
- Image shows a broken icon for guests only. The resource has
cacheControlset toPrivate. Change it toPublicand redeploy. - The stylesheet loads in preview but not on the published site. The resource was deployed after the last publish, or the path inside the zip is wrong. Check the case of folder names, because paths are case-sensitive. Publish the site again after deploying.
Cannot find module '@salesforce/label/c.Site_Welcome'. The label isn't deployed to the org, or the name is misspelled. Deploy the labels file and check the API name.- Label shows English for a French visitor. The label has no French translation, or the site doesn't list French as a supported language.
- A change to a static resource doesn't appear. The browser or CDN is serving a cached copy. Test in a private window, and avoid reusing the same file name with different content for large changes.
Practice
Exercise
A site component displays a logo from a zipped static resource named siteAssets. The logo loads for logged-in members but shows a broken image for guests. What is the most likely cause, and what is the fix?
Show answer
The static resource's cache control is probably Private, which prevents guests from retrieving it reliably. Set cacheControl to Public in siteAssets.resource-meta.xml, redeploy, and publish the site again.
Exercise
You need a component to show one of ten status messages, each stored as its own custom label. A teammate proposes building the label import path from the status code at runtime. Why won't that work, and what should you do?
Show answer
@salesforce/label imports must use a literal path, so a path built at runtime is not supported. Import all ten labels statically and put them in an object keyed by status code, then look up the right one at runtime.
Exercise
Why should you give the CSS classes in a stylesheet loaded with loadStyle a specific prefix, such as .brand-banner?
Show answer
A stylesheet loaded with loadStyle applies to the page rather than only to your component's shadow tree. Generic class names such as .title could restyle other components, so a specific prefix avoids collisions.