@swell/themes-sdk
v2.0.0-alpha.0
Published
Swell theme rendering SDK.
Readme
Swell Themes SDK
The Swell Themes SDK is a TypeScript-based library designed to simplify the development of isomorphic Swell apps by providing streamlined API access, theme rendering capabilities, and comprehensive caching solutions.
Previously published as @swell/apps-sdk 1.x.
Features
Core functionality
- Unified API access - Seamless integration with both Swell Backend API and Storefront API
- Authentication handling - Uses scoped access tokens supplied by Swell's proxy
- Theme rendering - Complete Shopify-compatible theme system with Liquid templating
- Resource management - Deferred loading of storefront resources (products, categories, etc.)
- Caching system - Multi-tier caching with Cloudflare KV integration
- Shopify compatibility - Full compatibility layer for migrating Shopify themes and apps
Theme capabilities
- Liquid templating - Enhanced Liquid engine with Swell-specific objects and filters
- Section rendering - Dynamic section management with schema support
- Settings resolution - Automatic theme and section settings processing
- Layout system - Flexible layout rendering with section groups
- Asset management - Optimized asset loading and URL generation
- Localization - Multi-language support with translation rendering
Developer experience
- TypeScript support - Full type safety with comprehensive type definitions
- Isomorphic design - Works seamlessly in both browser and server environments
- Error handling - Robust error management with detailed debugging information
- Performance optimized - Built-in caching and resource optimization
- Extensible architecture - Plugin system for custom resource types
Installation
npm install @swell/themes-sdk@nextRequires Node.js 22.22.2 or later for development and Node deployments.
Getting started
Basic setup
import { Swell } from '@swell/themes-sdk';
// Initialize Swell instance for the current server request
const swell = new Swell({
url: context.request.url,
serverHeaders: context.request.headers, // Headers from worker environment
});
// Make backend API calls
const products = await swell.backend.get('/products');
// Make storefront API calls
const cart = await swell.storefront.get('/cart');Headers and app proxying
When your Swell app is deployed, it runs behind Swell's proxy infrastructure. The proxy automatically injects essential headers that contain authentication tokens, store configuration, and storefront context. These headers are critical for the SDK to function properly:
// Headers passed from Swell's proxy contain:
// - swell-store-id: The store identifier
// - swell-public-key: Frontend API access key
// - swell-access-token: Backend API access token (scoped to app permissions)
// - swell-api-host: Backend API host
// - swell-storefront-id: Current storefront instance
// - swell-environment-id: Environment (development, staging, production)
// - swell-theme-id: Active theme identifier
// - swell-storefront-context: Preloaded cart/account data
const swell = new Swell({
url: context.request.url,
serverHeaders: context.request.headers, // Contains all proxy-injected headers
getCookie: (name) => getCookieValue(name),
setCookie: (name, value, options) => setCookieValue(name, value, options),
});Without these headers, the SDK cannot:
- Authenticate with Swell APIs
- Determine which store and storefront to operate on
- Access cached resources or maintain session state
- Render themes with proper configuration
The serverHeaders parameter should always be passed the complete headers object from your app's trusted proxy request context to ensure full functionality. The SDK does not authenticate these headers; server initialization requires backend credentials and an API host.
getCookie must reflect current state, including pending writes and deletions. setCookie owns cookie attributes and write policy, and receives the current Swell instance as its fourth argument. A missing server writer skips writes.
Theme rendering
import { Swell, SwellTheme, ProductResource } from '@swell/themes-sdk';
const swell = new Swell({
url: context.request.url,
serverHeaders: context.request.headers,
...options,
});
// Initialize theme with optional configuration
const theme = new SwellTheme(swell, {
forms: formConfigs,
resources: customResources,
globals: additionalGlobals,
});
// Fetch settings and set global context
await theme.initGlobals('product'); // page ID
// Create page data with deferred resource loading
const data = {
product: new ProductResource(swell, context.params.id),
};
// Render theme page
const renderedPage = await theme.renderPage(data);API reference
Swell class
The main entry point for SDK functionality:
class Swell {
// API access
backend?: SwellBackendAPI;
storefront: SwellClient<'snake'>;
// Configuration
config?: SwellAppConfig;
url: URL;
headers: Record<string, string | undefined>;
queryParams: ParsedQs;
// State
isEditor: boolean;
isPreview: boolean;
storefrontContext: SwellData;
// Methods
get<T>(url: string, query?: SwellData): Promise<T | undefined>;
post<T>(url: string, data: SwellData): Promise<T | undefined>;
put<T>(url: string, data: SwellData): Promise<T | undefined>;
delete<T>(url: string, data?: SwellData): Promise<T | undefined>;
getCachedResource<T>(key: string, args: unknown[], handler: () => T | Promise<T>, isCacheble?: boolean): Promise<T | undefined>;
}SwellTheme class
Handles theme rendering and management:
class SwellTheme {
// Core properties
swell: Swell;
globals: ThemeGlobals;
liquidSwell: LiquidSwell;
// Methods
initGlobals(pageId: string, options?: ThemeInitGlobalsOptions): Promise<void>;
renderPage(pageData?: SwellData, altTemplateId?: string): Promise<string | ThemePageTemplateConfig>;
renderSection(sectionId: string, pageData?: SwellData): Promise<string | ThemePageTemplateConfig>;
renderLayout(layoutName?: string, data?: SwellData, contentForLayout?: string, contentForHeader?: string): Promise<string>;
getSectionSchema(sectionName: string): Promise<Partial<ThemeSectionSchema> | undefined>;
setGlobals(globals: Partial<ThemeGlobals>): void;
}Resource classes
Built-in storefront resource classes for deferred loading:
Standard resources
AccountResource- Customer account managementBlogResource- Blog post contentBlogCategoryResource- Blog categorizationCartResource- Shopping cart stateCategoryResource- Product categoriesAccountOrderResource- Order informationPageResource- Static pagesProductResource- Product detailsVariantResource- Product variants
Primitive resources
SwellStorefrontCollection- Collection results with paginationSwellStorefrontRecord- Individual recordsSwellStorefrontSingleton- Unique resources (cart, account)
// Create custom resource class
class MyAppCollection extends SwellStorefrontCollection {
constructor(swell: Swell, query: SwellData = {}) {
super(swell, 'my-app-collection', query);
return this._getProxy();
}
}
// Usage in theme data
const data = {
myCollection: new MyAppCollection(swell, { limit: 20 }),
};Caching
Memory caching
Resources are automatically cached in memory per worker instance:
// Cached resource with custom handler
const cachedData = await swell.getCachedResource(
'expensive-operation',
[param1, param2],
async () => {
return await performExpensiveOperation(param1, param2);
}
);Cloudflare KV caching
For production scalability, enable KV caching:
const swell = new Swell({
url: context.request.url,
serverHeaders: context.request.headers,
workerEnv: context.locals.runtime.env, // Contains THEME KV binding
workerCtx: context.locals.runtime.ctx, // Worker context
});Cache invalidation
Cache behavior depends on the resource:
- Catalog request caches are separated by storefront instance and account group, with background refresh. Background refreshes update cached data without writing cookies.
- Cart and account requests bypass the catalog request cache.
- Mutations clear the affected preloaded storefront context.
Shopify compatibility
The SDK includes comprehensive Shopify compatibility for theme migration.
Supported Shopify features
- Template mapping - Direct file path compatibility
- Liquid objects - Full object structure compatibility
- Form handling - Compatible form endpoints and validation
- Section schemas - Shopify section configuration format
- Settings data -
settings_data.jsonandsettings_schema.json
Liquid templating
Enhanced Liquid templating with Swell-specific features. See Swell Liquid documentation for details.
Performance optimization
Lazy loading
Resources are loaded only when accessed in templates:
<!-- Product data is fetched only when this line executes -->
{{ product.name }}
<!-- Collection is fetched only when iteration begins -->
{% for item in collection.products %}
{{ item.name }}
{% endfor %}Development
Building the SDK
# Install dependencies
npm ci
# Build for production
npm run build
# Watch for changes
npm run watch
# Run tests
npm test
# Check types
npm run typecheck
# Build and run transport and cookie-adapter integration tests
npm run test:integration
# Build and check the packed package in an isolated consumer
npm run test:package
# Run all verification checks
npm run verifyIntegration tests in test/integration/ use the installed clients with intercepted network requests; no live store is needed. Run npm run test:cookies after building to check only the cookie adapters.
Project structure
src/
├── api.ts # Core Swell class and API handling
├── theme.ts # SwellTheme class and rendering
├── resources.ts # Storefront resource classes
├── liquid/ # Liquid templating engine
├── compatibility/ # Shopify compatibility layer
├── cache/ # Caching implementations
├── utils/ # Utility functions
└── index.ts # Main exportsResources
📄 License
See the LICENSE file for details.
