Component caching and offline API

Component caching and offline API

When a portal has offline support enabled, the offline worker on the device caches reads and queues writes for it. Standard components get this for free. Custom components opt in by adding two request headers and, optionally, listening for two notifications.

Read Offline support and caching first for what the strategies mean and how to enable the feature. Everything on this page only applies when Caching_Strategy__c on the Web_Portal__c record is something other than NetworkOnly.

Standard components

The standard components all call Apex through a shared helper, callComponent:

callComponent(apexClass, endp, {
    configId,
    recordId,
    onUpdate,
    ...params
});
Option Purpose
apexClass The Apex class to route to, for example b3p.PortalDataComponents.
endp The action on that class, for example getRecords.
configId The component's config-id attribute, used to resolve its saved configuration.
recordId The context record, where the component has one.
onUpdate Called when the offline worker refreshes a cached read in the background and the data has changed.
any other key Passed through to the Apex action as a parameter.

Two things happen automatically:

getReportList participates in the read cache. getReportData is excluded from caching and offline queues, so opening a report requires a connection.

The Chart component does not go through callComponent, but its data provider call opts into the same read cache, so charts render offline from their last successful load.

This helper is internal to the standard components and is not available to custom components. The example shows how a standard component uses it:

const rows = await callComponent('b3p.PortalDataComponents', 'getRecords', {
    configId: this.configId,
    recordId: this.recordId,
    onUpdate: (fresh) => {
        // The worker refreshed the cached response in the background and the data changed.
        this.rows = fresh.records;
    }
});

const result = await callComponent('b3p.PortalDataComponents', 'saveRecord', {
    configId: this.configId,
    record: { Id: rowId, Status__c: 'Complete' }
});

if (result.queued) {
    // Offline. The change is on the device and will be sent on reconnect.
    // The portal has already shown the user a toast, so do not show your own.
}

Custom components

A custom component that calls Apex directly participates by following four rules.

1. Call the router over REST

Post to the router REST endpoint on the Site domain:

POST <site>/services/apexrest/b3p/GlobalRemotingRouter/
Content-Type: application/json
{
    "controllerName": "b3p.MyClass",
    "endp": "myAction",
    "sessionKey": "<portal-session-key>",
    "recordId": "<record-id>"
}

Send no Authorization header for guest traffic. The sessionKey in the body is what identifies the portal user.

The response is the standard router envelope, double encoded: the HTTP body is a JSON string whose content is the envelope JSON.

HTTP/1.1 200 OK
Content-Type: application/json

"{\"success\":true,\"queued\":false,\"responseObject\":{\"records\":[{\"Id\":\"<record-id>\",\"Name\":\"Acme\"}]}}"

So the client parses twice:

const envelope = JSON.parse(JSON.parse(await response.text()));

2. Mark cacheable reads with a cache key

Send an X-Portal-Cache-Key header whose value is the SHA-256 hex digest of the exact JSON body string you are posting. The worker stores the response under that key.

X-Portal-Cache-Key: 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08

Omit the header for anything that must not be cached, for example an action with side effects, a one time token exchange, or anything user specific you do not want persisted on the device.

Because the key is derived from the whole body, and the body includes sessionKey, caches are naturally scoped per user. Two different portal users on the same device never read each other's cached responses.

3. Mark queueable writes

Send X-Portal-Sync: 1 on a write you want queued when the device is offline.

X-Portal-Sync: 1

When the network is unavailable the worker answers immediately with 202 and this body:

HTTP/1.1 202 Accepted
Content-Type: application/json

"{\"success\":true,\"queued\":true,\"responseObject\":null}"

Same double encoding as a normal REST response, so your existing parsing works. Check queued and update the interface optimistically. The portal already shows the user a toast, so do not add your own.

Only send X-Portal-Sync: 1 on an action that is safe to run later, against a stale record state, and possibly out of order with respect to other queued work. File uploads must not use it.

4. Complete fetch example

async function callPortal(controllerName, endp, params, { cacheable, queueable } = {}) {
    const body = JSON.stringify({
        controllerName,
        endp,
        sessionKey: window.globals.sessionKey,
        ...params
    });

    const headers = { 'Content-Type': 'application/json' };

    if (cacheable) {
        headers['X-Portal-Cache-Key'] = await sha256Hex(body);
    }
    if (queueable) {
        headers['X-Portal-Sync'] = '1';
    }

    const response = await fetch(
        `${window.globals.siteUrl}/services/apexrest/b3p/GlobalRemotingRouter/`,
        { method: 'POST', headers, body }
    );

    // The router returns a JSON string containing the envelope JSON.
    const envelope = JSON.parse(JSON.parse(await response.text()));

    if (!envelope.success) {
        throw new Error(envelope.message || 'Portal call failed');
    }
    return envelope;
}

async function sha256Hex(text) {
    const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text));
    return Array.from(new Uint8Array(digest))
        .map((b) => b.toString(16).padStart(2, '0'))
        .join('');
}

Note that the header value must be the digest of the byte for byte string you actually send as the body. Build the body string once, hash that string, and post that same string. Re-serialising the object a second time can reorder keys and produce a key that never matches.

Requests that must use the network

From 11.2.0, the worker recognises X-Portal-Network-Only: 1 on same-origin router REST POSTs. This route takes precedence over caching and background sync, so a failed network request is neither served from cache nor queued.

The standard components' request helper applies this automatically to b3p.Portal actions whose names start with passkey: it ignores caching options, adds the header on REST requests and uses fetch with cache: 'no-store'. The Apex passkey response also sets Cache-Control: no-store. Custom integrations calling these endpoints directly must preserve this behaviour and must not cache credentials or queue authentication attempts. See Passkey login.

Hearing about background refreshes

Under Stale While Revalidate the worker answers from cache and then refreshes. To pick up the fresh data, open a broadcast channel named portal-cache-updates:

const channel = new BroadcastChannel('portal-cache-updates');

channel.onmessage = (event) => {
    const { type, key, body } = event.data;
    if (type === 'CACHE_UPDATED' && key === myCacheKey) {
        const envelope = JSON.parse(JSON.parse(body));
        render(envelope.responseObject);
    }
};
Field Meaning
type Always CACHE_UPDATED.
key The cache key you sent in X-Portal-Cache-Key, so you can match the message to your request.
body The fresh response text, in the same double encoded form as an HTTP response.

Keep the cache key you computed for a request so you can compare against key. Messages only fire when the refreshed data actually differs from what was cached.

Hearing about connectivity and replayed writes

Two events are published on the portal event bus, the window.eventListeners based publish and subscribe channel the portal apps share.

Event Detail Meaning
connectivityChange { online: true | false } The device went offline or came back online.
backgroundSyncComplete { count: 3 } The queue was replayed. count is the number of writes sent.
EventBus.subscribe('connectivityChange', ({ detail }) => {
    this.readOnly = !detail.online;
});

EventBus.subscribe('backgroundSyncComplete', ({ detail }) => {
    // Queued requests were sent. Reload and verify the resulting records.
    console.log(`${detail.count} queued changes were sent`);
    this.refresh();
});

The worker also posts a message to any registered service worker message listener, which is useful for code that is not on the event bus:

navigator.serviceWorker.addEventListener('message', (event) => {
    if (event.data && event.data.type === 'SYNC_REPLAYED') {
        refresh(event.data.count);
    }
});

The replay count reports requests sent, not successful Salesforce saves. An HTTP response removes a request from the queue even if its envelope reports an error. Refresh after backgroundSyncComplete to verify the changes and show server assigned ids, formula fields and roll ups for successful saves.

What gets cached, and what does not

Checklist for a custom component