Skip to content

Storefront widgets

A storefront widget is a page of your plugin that a shop shows in a frame on its storefront: on a product page, in the cart, on any page the merchant places it, or in the shopper's account area. The frame is cross-origin and gets no session token, so the widget asks the page around it for what it needs, through the widget bridge.

The storefront-widget starter is a working example: npx @orbitcommerce/plugin-cli create my-widget --template storefront-widget. The tool that makes it is described in The orbit-plugin tool.

The storefront targets

TargetWhere it showsValues in its URLHandlePlaceable
storefront.product.widgetThe product pagestoreId, productId, variantId, themeNoYes
storefront.cart.widgetThe cart page or drawerstoreId, cartId, themeNoYes
storefront.page.blockAny storefront page the merchant places it onstoreId, pageHandle, themeNoYes
storefront.account.sectionThe shopper's account area, at /account/<handle>storeId, theme, pageHandleYesNo
storefront.global.embedEvery storefront page, as an overlay the layout injectsstoreId and public settings: see The global embedNoNo

The storefront appends those values as query parameters to the URL it loads. They are not verified: anyone can open your widget URL with any values, so never authorise anything on them.

An account section's handle is its path segment: 2 to 40 characters, lowercase letters, digits or hyphens, starting with a letter. It is the only target that needs a handle on its extension point. Core account pages and the account layout's own names are reserved, so a section cannot shadow orders, profile or sections. While the plugin is active, the account menu lists the section with its extension point label and icon, and pageHandle is account/<handle>.

All five targets are declarable in extensionPoints; only the placeable ones are offered in the page builder.

The global embed

storefront.global.embed is not a frame in the page's content. The layout lays its frame over the whole viewport on every storefront page, with pointer-events: none and aria-hidden, so shoppers see it but cannot click into it or focus it. It suits decoration, such as falling snow.

  • Its sandbox is allow-scripts allow-same-origin, with no allow-popups, and it is granted no permissions (allow=""). To open a page in a new tab, ask the page with navigate(url, { target: 'blank' }).
  • Its URL carries storeId and no theme. It also carries the merchant's values for the settings intensity, color, birthday, date, dates, always, size and duration, when your settingsSchema marks them public (see Settings a widget may read). A public enabled setting set to false hides the overlay.
  • Its URL must be on one of the origins your plugin declares (any origin while it declares none yet), over https, or over plain http only on a loopback host. An embed on the shop page's own origin is not framed.
  • The page answers only ORBIT_WIDGET_NAVIGATE from it. Resizes are ignored, and context and customer token requests get no answer, so the bridge settles them to null when they time out.

The page also posts two messages of its own into the frame, addressed to the embed's origin. Read them in a message listener that checks event.source === window.parent.

MessageWhenCarries
ORBIT_HOST_SCROLLWhen the frame is set up, on each load of the frame, and as the page scrolls (at most once per animation frame){ type, scrollY }: the page's window.scrollY
ORBIT_CUSTOMEROn each load of the frame, only when the page knows the signed-in shopper's birthday{ type, birthday }: the birthday as a string

The widget bridge

Import the bridge from @orbitcommerce/sdk/widget in code that runs inside the frame:

TypeScript
import { createWidgetBridge } from '@orbitcommerce/sdk/widget';

const widget = createWidgetBridge({ pluginId: 'acme-points' });

That entry loads only the bridge. The package root also creates the default dashboard client, which a storefront page has no use for. The entry is for bundled browser code: Node's own ES module loader cannot import it, and nothing on your server needs it.

The bridge speaks to the page over postMessage. The page answers only the frame it created, on the origin of the URL it loaded, and stamps each reply with the id of the plugin it embedded. The bridge reads a reply only from window.parent and matches it to its request by requestId. Every message the bridge posts carries pluginId, which the page ignores in favour of the id it embedded. Outside a frame there is nobody to ask, so requests settle at once and resizes are dropped. Call widget.dispose() when your page unmounts.

The dashboard look in Looking like Orbit does not apply here: a widget sits in the shop, and the shop's own theme decides how it looks.

Size the frame

The frame is only as tall as you say. Report the height of a wrapper element whenever it changes:

TypeScript
const stop = widget.observeHeight(document.getElementById('app')!);
// or, by hand
widget.resize(640);

observeHeight returns a function that stops observing. Reports are debounced, rounded up and capped at WIDGET_MAX_HEIGHT (10000 px), and a repeat of the last height is not sent. The storefront never makes the frame shorter than its own minimum: 400 px for an account section.

To hear what the page applied, use resizeAndWait(). It sends the height at once, not debounced, with a request id, and resolves the page's answer:

TypeScript
const result = await widget.resizeAndWait(list.scrollHeight);
// { success: true, height: 2400, maxHeight: 10000 }, or
// { success: false, error, maxHeight } (the frame kept its height), or
// null: the page predates the answer (it still applied the height)
if (result && list.scrollHeight > result.maxHeight) showNextPageButton();

The page never clamps: a height above its cap (maxHeight, 10000 px today) or below 1 is ignored, and the frame keeps the height it had. The SDK caps what it sends at WIDGET_MAX_HEIGHT, so a taller widget gets the tallest frame. Page or batch long lists so they fit under maxHeight rather than relying on the frame to grow. A height that is not a finite number above 0 rejects with a TypeError.

Move the shopper

The frame is sandboxed (allow-scripts allow-same-origin allow-popups; the global embed's has no allow-popups), so it cannot move the store page. A link with target="_top" or target="_parent" does nothing, writing window.top.location throws a SecurityError, a <form> cannot submit, alert(), confirm() and prompt() do nothing, downloads are blocked, and a target="_blank" link opens a tab that carries the same sandbox.

Ask the page instead:

TypeScript
button.addEventListener('click', async () => {
  const result = await widget.navigate('/account/orders'); // or { target: 'blank' }
  if (result === null) showPlainLink('/account/orders'); // an older page: no answer
  else if (!result.success) console.warn(result.error);
});

navigate(url, { target }) posts ORBIT_WIDGET_NAVIGATE and resolves { success: true }, { success: false, error }, or null when nothing answers within two seconds (WIDGET_NAVIGATE_TIMEOUT_MS; timeoutMs changes it). On null, show the shopper a plain link: navigate() never falls back by itself.

A relative URL is a page of the shop and opens in the same tab, unless target is 'blank'. A URL on any other site opens in a new tab with noopener and noreferrer, whatever target says. Only http and https URLs of at most 2048 characters are followed; anything else rejects with a TypeError before a message is posted.

The page moves its own tab only straight after the shopper clicks, taps or types on it, so call navigate() from that handler, before any slow await. Otherwise the answer is success: false with the page's reason. In a new tab, success: true means the page asked the browser to open it; a popup blocker can still stop it.

Read the page's context

TypeScript
const context = await widget.requestContext();
// { currency: { code, symbol, symbolPosition } or null,
//   vat: { showExVat, rateLabel, pricesIncludeTax },
//   customer: { authenticated, b2b }, pageUrl, query } or null

Use it to format prices and labels the way the page does. rateLabel and pricesIncludeTax are null when the store has no usable tax setup: then show no VAT label and convert nothing. It is a hint for presentation, not proof of anything: customer.authenticated and b2b are not verified, and neither are the query parameters in your frame's own URL (storeId, theme, pageHandle), which anyone can open with any values.

pageUrl is the host page's origin and path only, never its query string or fragment: the storefront carries order access and password reset tokens in its query strings, and your widget is code on another origin. A host from before that rule sent the whole address.

To read a query parameter of the page, such as your own share-link parameters, name it:

TypeScript
const context = await widget.requestContext({ queryKeys: ['build', 'ar'] });
context?.query; // { build: 'm1.m4.c2' } when the page is .../sofas?build=m1.m4.c2

Up to 10 names (WIDGET_MAX_QUERY_KEYS), each lowercase, starting with a letter and at most 32 characters (WIDGET_QUERY_KEY_PATTERN); duplicates are sent once. Anything else rejects with a TypeError before a message is posted. queryKeys is sent only when the list is not empty.

query holds the page's first value for each name it carries, decoded. A name the host withholds reads exactly like one the page does not carry: the host never answers anything that could be a credential or the shopper's details (token, code, key, email, orderid, session, any name containing token, secret, password or key), a value that looks like a JWT, or one over 4096 characters (WIDGET_MAX_QUERY_VALUE_LENGTH, also the longest share-link value a widget may write, so what you write you can read back).

query is null when the reply carries none: you named no keys, or the host predates them. Like every query parameter, the values are unverified.

To write share-link parameters into the page's address, post ORBIT_WIDGET_STATE (see The messages). Use lowercase names: the page also writes upper case ones, but queryKeys reads back lowercase names only.

The messages

The bridge wraps the resize, context, customer token and navigate messages, so you do not post those yourself. Their names are in WIDGET_MESSAGE_TYPES.

MessageDirectionCarries
ORBIT_WIDGET_RESIZEwidget to page{ height }, or { height, requestId }; a reply only with a string requestId
ORBIT_WIDGET_RESIZE_RESULTpage to widget{ pluginId, requestId, success, height?, maxHeight, error? }
ORBIT_WIDGET_CONTEXT_REQUESTwidget to page{ requestId, queryKeys? }
ORBIT_WIDGET_CONTEXTpage to widget{ pluginId, requestId, currency, vat, customer, pageUrl, query? }
ORBIT_WIDGET_CUSTOMER_TOKEN_REQUESTwidget to page{ requestId }
ORBIT_WIDGET_CUSTOMER_TOKENpage to widget{ pluginId, requestId, token, expiresIn? }
ORBIT_WIDGET_NAVIGATEwidget to page{ url, target?, requestId }
ORBIT_WIDGET_NAVIGATE_RESULTpage to widget{ success, error?, requestId, pluginId? }

An older page sends no pluginId on a navigate result; the bridge matches it by requestId. A page that predates the other requests leaves them unanswered, and the bridge settles each one to a quiet default rather than hanging. The customer token only ever travels page to widget.

The bridge does not wrap the cart, price and share-link messages. Post those to window.parent yourself, and read a reply only when event.source is window.parent and its pluginId is your plugin's id.

MessageDirectionCarries
ORBIT_WIDGET_ADD_TO_CARTwidget to page{ productId, variantId?, quantity, requestId? }
ORBIT_WIDGET_ADD_TO_CART_RESULTpage to widget{ pluginId, requestId?, success, error? }
ORBIT_WIDGET_ADD_ITEMS_TO_CARTwidget to page{ requestId, lines: [{ productId, variantId?, quantity }] }
ORBIT_WIDGET_ADD_ITEMS_TO_CART_RESULTpage to widget{ pluginId, requestId, results: [{ success, error?, unconfirmed? }] }
ORBIT_WIDGET_PRICES_REQUESTwidget to page{ requestId, productIds }
ORBIT_WIDGET_PRICESpage to widget{ pluginId, requestId, prices, error? }
ORBIT_WIDGET_STATEwidget to page{ params: { [name]: string or null } }; no reply

Every reply carries the id of the plugin the page embedded, and the request's requestId when it sent a string one.

  • ORBIT_WIDGET_ADD_TO_CART puts one product in the shopper's cart. quantity is rounded down to a whole number of at least 1. On a failure, error gives the page's reason.
  • ORBIT_WIDGET_ADD_ITEMS_TO_CART adds 1 to 100 lines in one go and answers one result per line, in the order sent. A message with no lines, an unusable line or more than 100 lines adds nothing and gets a single result. The add is not all or nothing: the cart keeps the lines added before the first one that failed. A line with unconfirmed: true may be in the cart, so the shopper should look before adding it again. An error such as B2B_LOGIN_REQUIRED means the page is already showing its own sign-in or verification prompt.
  • ORBIT_WIDGET_PRICES_REQUEST asks for the signed-in buyer's negotiated prices, for up to 200 product ids. prices maps each product id to the price the storefront resolves for it. It is {} for a guest or a failed lookup, and for more than 200 ids, with error: 'Too many products requested'.
  • ORBIT_WIDGET_STATE writes the values into the page's query string, so the address bar holds a share link; null removes a name. Up to 8 names, each a letter followed by up to 31 letters, digits, _ or -; values up to 4096 characters; and the whole query at most 16384 characters. Anything else refuses the whole message. The names share the query with the storefront's own parameters (q, page, sort, variant and others), so pick names that cannot collide with them.

The product, cart and page block widgets and the account section handle every widget to page message in these tables. Where the page has no cart, a cart message is answered with success: false. The global embed answers only ORBIT_WIDGET_NAVIGATE.

Who the shopper is

The page will not give you its session, and a cross-origin frame gets no session token, so do not construct an OrbitClient in the widget. To know who the shopper is, ask for a customer token and send it to your own server with each request:

TypeScript
async function callMyApi(path: string, init: RequestInit = {}) {
  const send = (token: string) =>
    fetch(path, {
      ...init,
      headers: { ...init.headers, Authorization: `Bearer ${token}` },
    });

  const token = await widget.getCustomerToken();
  if (!token) return null; // signed out: show a sign-in prompt

  let response = await send(token);
  if (response.status === 401) {
    // Once only: ask the page again, then give up.
    const fresh = await widget.getCustomerToken({ forceRefresh: true });
    if (!fresh) return null;
    response = await send(fresh);
  }
  return response;
}

getCustomerToken() keeps the token in memory, asks the page for a new one a minute before it expires, and shares one request between every caller. Tokens live ten minutes. It resolves null when nobody is signed in, when your plugin is not active on the store or has not been granted customer:read, and when the page does not answer within five seconds. A frame served from the store page's own origin is never given one: only a widget on an origin of its own is. Never write the token to storage, a cookie, a URL or a log.

Verify it on your server with OrbitClient.verifyCustomerToken:

TypeScript
import { OrbitClient, CustomerTokenError } from '@orbitcommerce/sdk';

export async function GET(request: Request) {
  const token = request.headers.get('authorization')?.replace(/^Bearer /, '') ?? '';
  try {
    const shopper = await OrbitClient.verifyCustomerToken(token, {
      pluginId: 'acme-points', // your manifest pluginId: always pass it
    });
    return Response.json(await loadPoints(shopper.storeId, shopper.customerId));
  } catch (error) {
    if (error instanceof CustomerTokenError) {
      return Response.json({ error: error.reason }, { status: error.status });
    }
    throw error;
  }
}

It returns { storeId, pluginId, customerId, companyId, contactId, expiresAt }, with expiresAt in Unix seconds. Always pass pluginId: a token minted for another plugin is refused (wrong_plugin), so a token lifted from another plugin's frame cannot be replayed against your server. CustomerTokenError.reason is missing, invalid, wrong_plugin (status 401) or unreachable (status 503, when the Orbit API could not be asked).

The token names a shopper and grants nothing. It is not an API credential: read the shopper's data with the access token you stored for storeId, scoped to that customerId. Staff and customer tokens are not interchangeable: verifyToken refuses a customer token and verifyCustomerToken refuses a staff token, so a shopper can never pass your admin routes.

For a shopper in a B2B company, companyId and contactId name the company and their contact record in it; otherwise both are null. A success is cached for at most a minute and never past the token's expiry; a refusal is never cached. A token also stops verifying once the customer it names has been deleted or erased or is no longer in the store, once the company membership it names has ended, and once the store has closed. Each is refused as invalid, like a forged token, so a refusal never says whether the customer existed. The store page never hands out a token for a deleted or erased customer.

OrbitClient itself is described in The SDK.

Settings a widget may read

Mark a field "public": true in your settingsSchema when shoppers may see its value, such as a headline or a colour. Only a literal true counts. Every other field stays private to your plugin and the merchant, and the storefront never receives it, so never mark a field public that holds an API key, a password or an email address.

Read settings on your widget's server, through the store's own connection. The storefront-widget starter marks its headline public; its widget page looks the headline up with the store's stored credential (orbitFor(storeId), then settings.get()), keeps each store's answer for a minute, and falls back to the schema default when the store has not connected yet. The storeId in the widget's address is not verified, so it only ever chooses which store's public headline to show.

Being framed by a shop's own domain

Orbit's dashboard and hosted storefronts are platform hosts, and a shop can also answer on its own domain. The browser checks frame-ancestors against every page above the frame, starting with the page that frames it, so one fixed list cannot cover a custom domain without allowing every domain. The SDK builds the list per request:

TypeScript
import { NextResponse, type NextRequest } from 'next/server';
import { frameAncestorsHeader, widgetFrameAncestors } from '@orbitcommerce/sdk/csp';
import { orbitApiUrl } from '@/lib/env';

export const config = { matcher: ['/widget', '/widget/:path*'], runtime: 'nodejs' };

// The shared header in next.config.ts leaves /widget out, because a shop on its own domain can frame
// the widget only when Orbit confirms the domain is that store's, so the header is worked out per request.
export async function middleware(request: NextRequest): Promise<NextResponse> {
  const sources = await widgetFrameAncestors(request.headers.get('referer'), {
    storeId: request.nextUrl.searchParams.get('storeId'),
    apiUrl: orbitApiUrl(),
  });
  const response = NextResponse.next();
  response.headers.set('Content-Security-Policy', frameAncestorsHeader(sources));
  return response;
}

The storefront-widget starter ships this middleware, with that matcher and runtime: 'nodejs', so its widget routes answer with a list that fits each request. orbitApiUrl() is the starter's helper for the API address.

widgetFrameAncestors(referer, { storeId }) starts from PLATFORM_FRAME_ANCESTORS. A platform host gets that list without asking the API. For any other referer it asks the public API whether the host is an active custom domain. It adds the origin when the answer is yes, and, if you passed storeId, only when the domain belongs to that store. A hit is cached for five minutes and a miss for one. A failed lookup is not cached and gives the platform list. It never throws.

frameAncestorsHeader(sources) returns frame-ancestors <source> <source> .... Set it as the Content-Security-Policy header of the widget response. clearFrameAncestorsCache() empties the cache; the starter's tests use it. The API address is the usual order: the apiUrl option, ORBIT_API_URL, NEXT_PUBLIC_ORBIT_API_URL, then https://api.myorbitcommerce.net.

PLATFORM_FRAME_ANCESTORS admits every host under orbitcommerce.net and myorbitcommerce.net, and localhost and its subdomains on any port. Every shop's storefront address is under myorbitcommerce.net, so any shop on the platform can frame your widget, with any storeId in its URL. Nothing the page around your widget sends proves which shop or shopper it is: only a customer token verified on your server does.

A store in embed mode answers with frame-ancestors *, so any website can frame its pages. The website that frames such a store is above your widget too, and it is not in your list, so a widget on an embed-mode store page that another website frames is refused by this header.

Placing it

A placeable widget is added by the merchant in the page builder: a product widget on a product page, a cart widget in the cart, a page block on any page. The account section and the global embed are not placeable: the account section shows at /account/<handle> and in the account menu while the plugin is active, and the layout injects the global embed on every storefront page.

Where each target appears is listed in Where plugins appear. The storefront-widget starter is the example to copy.