Apps
The Swell Apps SDK is a Typescript-based library built to simplify the implementation of an app frontend by taking care of API access and more. In the case of storefront apps, it encapsulates many aspects of theme rendering and caching.
We recommend referring to Proxima app as a production example of all the different ways to integrate with Apps SDK.
While this guide can help you understand the features and use cases of the library, a full reference for Apps SDK is not yet available.
The primary feature of Apps SDK is to simplify authentication between your app and the store which has installed it.
Here's an example of instantiating the Swell class using headers passed to an app frontend instance, followed by a simple API call:
import { Swell } from '@swell/apps-sdk';
const swell = new Swell({
serverHeaders: context.request.headers, // Object received from worker environment
...options,
});
// Make a backend API call
await swell.backend.get('/products');
// Make a frontend API call
await swell.storefront.get('/products');The access token provided via headers gives your app scoped access based on its requested permissions when installed. If it is granted full-permissions, then you can consider the backend API to function just as any secret key would provide.
The most common approach is to initialize a Swell class instance in the beginning of the request cycle, then pass the instance through the request context for page rendering or other components that require API access.
Besides the Proxima app example, an IDE such as Visual Studio Code should be able to help you to infer the different options available when instantiating the Swell class.
The ability to support themes is a key feature of Apps SDK. The library understands the Shopify theme structure, while your app frontend can implement any kind of logic and structure unique to your use case. This section outlines the different theme rendering features offered by Apps SDK.
The SwellTheme class is the entry-point for all theme rendering functionality. Here's a basic example:
import {
Swell,
SwellTheme,
SwellProduct,
} from '@swell/apps-sdk';
const swell = new Swell({
serverHeaders: context.request.headers, // Object received from worker environment
...options,
});
const theme = new SwellTheme(swell, [options]);
// Fetch settings and set global context objects
await theme.initGlobals('index');
const data = {
product: new SwellProduct(swell, context.params.id),
};
// Render a theme page with optional data
return await theme.renderPage([data]);There are several built-in classes representing storefront resources such as products, categories, etc, as well as primitive classes for customizing resource logic. A resource uses deferring fetching so that when a theme template is rendered, the data is not fetched unless it is used. This is preferable in themes because a theme developer can choose from many different resources to render a page, but may not need to use all of them.
Standard resources:
- SwellAccount
- SwellBlog
- SwellBlogCategory
- SwellCart
- SwellCategory
- SwellOrder
- SwellPage
- SwellProduct
- SwellVariant
Primitive resources are used to create your own resource objects, in the same way that standard resources are implemented in the SDK:
- SwellStorefrontCollection: A collection result.
- Arguments: swell: Swell, collection: string, query: object = {}, getter?: StorefrontCollectionGetter<T>
- SwellStorefrontRecord: A single record result from a collection.
- Arguments: swell: Swell, collection: string, id: string, query: object = {}, getter?: StorefrontCollectionGetter<T>
- SwellStorefrontSingleton: A unique record-type, for example SwellAccount and SwellCart.
- Arguments: swell: Swell, collection: string, getter?: StorefrontCollectionGetter<T>
Here's an example of how to create a custom resource class for a storefront collection defined by an app, by extending a core class:
import {
Swell,
SwellStorefrontCollection,
StorefrontResourceGetter,
} from '@swell/apps-sdk';
import type {
StorefrontResourceGetter,
SwellData,
SwellCollection,
} from 'types/swell';
export class MyAppCollection<
T extends SwellData = SwellCollection,
> extends SwellStorefrontCollection {
constructor(
swell: Swell,
id: string,
query: SwellData = {},
getter?: StorefrontResourceGetter<T>,
) {
// Wrap the collection name
super(swell, 'my-app-collection', id, query, getter);
// Return the proxy object with defers calls to async data
return this._getProxy();
}
}Some resources are automatically cached by the Swell class, in context of the worker instance. For a more efficient and scalable approach, you can create a Cloudflare KV binding called THEME and pass its context to the Swell class when instantiated. For example:
import { Swell } from '@swell/apps-sdk';
const swell = new Swell({
...
workerEnv: context.locals.runtime.env,
workerCtx: context.locals.runtime.ctx,
});In this example from an Astro frontend, env is an object containing the THEME KV binding, while ctx is a reference to the Worker context object.
More details about caching behavior and options coming soon.
A storefront app can show the blocks of a store's installed apps: widgets that apps declare in storefront.embeds in their swell.json and that merchants place on storefront pages. @swell/apps-sdk/blocks reads the declarations and runs script blocks in the page, and startComponentBlocks in @swell/apps-sdk/components mounts component blocks in frames. They need @swell/apps-sdk 2.1.2 or later.
The blocks module reads declarations by the same rules swell app push applies. A declaration that breaks one rule is left out whole, so a page never shows part of an app. See Storefront extensions for how apps declare and write blocks.
Read the store's installations on your server, with your installation's key, and pass them to readInstalledBlocks:
import { appFrontendOrigin, blockAllowedOn, blockCspSources, readInstalledBlocks } from '@swell/apps-sdk/blocks';
// On your server: GET /:clients/:self/apps?expand=app with your installation's key
const apps = readInstalledBlocks(installations, {
origin: (installationId) => appFrontendOrigin(context.adminUrl, context.storeId, installationId),
onProblem: (message) => console.warn(message),
});
blockAllowedOn(block, 'product'); // where a merchant may place a block, and where it renders
const csp = blockCspSources(scriptApps, componentApps); // { scriptSrc, connectSrc, imgSrc, frameSrc }Each entry has the app's slug and name, its blocks, its script URL and integrity, the connect and img origins its script uses, and, for component blocks, the frame origin they load from.
@swell/apps-sdk/blocks exports:
- readInstalledBlocks(raw, { origin, onProblem? }): the blocks of the store's installed, active apps from GET /:clients/:self/apps with app expanded, at most BLOCK_LIMITS.apps apps. An app whose declaration breaks a rule is left out and passed to onProblem.
- readAppBlocks(entry, options?): reads one app's entry whose script is already an https URL. Returns { ok: true, app } or { ok: false, problem }.
- appFrontendOrigin(adminUrl, storeId, installationId): the origin of an installation's frontend, where its block script and component frames load, or null.
- blockAllowedOn(block, page): whether a block may be placed and rendered on a page type. Uses the block's pages, or every page type except account.
- isComponentBlock(block): whether a block renders as a component in a frame.
- hasScriptBlocks(app): whether an app has script blocks, so its script loads on pages that hold one.
- blockCspSources(scripts, frames?): the Content Security Policy sources a page adds for its blocks, as { scriptSrc, connectSrc, imgSrc, frameSrc }.
- startBlockRegistry(options): starts the page's block registry. Returns a function that stops it and cleans up every block.
- BLOCK_LIMITS: the standard's limits, such as 10 apps per store, 20 blocks per app, and 20 props per block.
- BLOCK_PAGES: the page types a block's pages can list.
Render each placed block on the server as one element, with the fallback shoppers see before the block mounts as its children. Only your renderer should write these elements: don't let theme code or store content add data-app-* attributes.
<div class="swell-app-block" data-app-block="<app>/<block>" data-app-props="<json>">…fallback…</div>Set the theme tokens on each element as --swell-* custom properties. On a page that holds an app's blocks, add the sources from blockCspSources to its Content Security Policy, and load each app's script once, with its integrity, when the page holds one of its script blocks. Then start the runtimes:
import { startBlockRegistry } from '@swell/apps-sdk/blocks';
import { startComponentBlocks } from '@swell/apps-sdk/components';
startBlockRegistry({ apps: ['my_app'], storefront: { storeId, storefrontId, mode: 'live' } });
startComponentBlocks({
storeId,
publicKey: 'host', // a placeholder when url names your own route, which reads the list with your key
url: `${location.origin}/your-components`,
getToken: (app) => fetch(`/.swell/component-token?app=${app}`).then((r) => r.json()),
blocks: { 'my_app/gift_card_form': { component: 'GiftCardForm', title: 'Gift card form' } },
storefront: { storeId, storefrontId, mode: 'live' },
});startBlockRegistry({ apps, storefront, publicKey?, attribute?, document? }) makes window.SwellAppBlocks an object whose push registers an app's blocks, including registrations pushed before it started. It mounts each block on every matching element, now and when one is added later, such as in a cart drawer. It cleans up when the element leaves the page, and cleans up and mounts again when the props change. It ignores apps not listed in apps. Each mount gets { props, app, block, storefront, proxy }, where proxy is the app proxy's path on the page's origin.
startComponentBlocks({ storeId, publicKey, url?, getToken, blocks, storefront, attribute?, readyAttribute?, frameClass?, document? }) mounts each component block's App Component in a frame on its app's origin, with the block's props as params and { storefront, tokens } as context. getToken(app) returns the block's component token, which a storefront host fetches from /.swell/component-token?app=<app>. It sets data-app-frame-ready on the element once the frame is ready, so your CSS can hide the fallback, and unmounts the frame when the element leaves the page.
BLOCK_TOKENS lists the theme tokens passed as context.tokens: the names of the --swell-* custom properties without the prefix, such as color-text, font-body and radius. startComponentBlocks reads them from each element.
Both functions return a function that stops them and cleans up every block. Both take attribute for elements that name their block in another attribute.
We expect to continue growing Apps SDK to simplify more use cases over time. If you have any requests or ideas to improve the library, we welcome and appreciate discussions and pull-requests on Github.