Apps
Functions in Swell are powered by Cloudflare Workers and executed at the edge for optimal performance. Functions have no cold boots and do not require extra time to start up before executing your code. Since they run on the edge, they are optimal both for server-side webhooks and for serving personalized content directly to end-users.
You can create a new function by adding a JavaScript or TypeScript file in the app's functions/ folder, or by using the following CLI command:
swell create function→ See the CLI reference for more details and options.
Functions run with the Cloudflare Worker runtime, a high-performance environment designed for efficient and secure server-side execution. It offers a subset of Web APIs, including fetch, Request, and Response, optimized for minimal latency and quick execution. The runtime is not a complete Node.js environment and does not support certain Node.js APIs, such as reading or writing to the filesystem.
The platform can trigger functions in response to various platform events, providing a powerful way to implement App-specific logic within Swell. When an event occurs, the corresponding app webhook is triggered, executing the associated Function. This allows developers to handle a wide range of use cases, such as sending custom notifications, processing data, or integrating with third-party services.
Due to their nature, functions don't have access to all Node.js and Browser APIs. Developers need to use ES modules and avoid libraries that rely on dynamic code execution or unsupported Node.js APIs. Function restrictions include limits on initial response time, memory usage, code size, and environment variable sizes. Additionally, request properties such as URL length, request body length, and request headers are subject to constraints. As the Workers runtime evolves, it is expected that more Node.js APIs and functionality will become available, further enhancing the capabilities of app functions.
Functions must respond within 10 seconds by default. The timeout configuration accepts values from 1,000 to 20,000 milliseconds, and values above 10,000 require the functions.long_timeout feature to be enabled for the store. For work that outlasts the response window, respond immediately and continue processing in the background with req.context.waitUntil(), or split large jobs into smaller batches triggered by cron schedules or workflows.
Pricing for functions is based on the number of executions. There is no limit on the total number of function executions an app can make, but charges apply for executions above the store’s plan tier.
During local development, you'll be able to run app functions on your machine and quickly test changes using the following CLI command:
swell app devThis will perform several functions:
- Start a local proxy using localtunnel.me.
- Add the local proxy URL to your account session, which informs Swell that your app dev server is running and should receive events instead of a deployed version.
- Note: This command will also start a development server for an app frontend, if one exists.
You should only run app dev on one app at a time, otherwise your account session will only remember the last app that was started.
Events triggered by your Swell store will be routed to your local server, allowing you to observe and iterate on app logic.
There are a variety of triggers that can be utilized with functions that support a wide variety of applications.
Functions can be triggered by events from your data models. To connect a function to a model event, specify the model.events property with one or more event names. In the following example, we’re using the conditions property to narrow function invocations where the event stock_level property is being changed. Note the function is called asynchronously.
export const config: SwellConfig = {
description: 'Update product records when stock levels change',
model: {
events: ['product.created', 'product.updated', 'product.deleted'],
// conditions are checked against the record before calling the function
conditions: {
stock_level: { $exists: true },
},
// optional sequence number to prioritize among other function calls
// a lower number means higher priority
sequence: 1
},
};
export default function (req: SwellRequest) {
const { swell, data, session, store } = req;
...
}
For a full list of standard model events, see the event types reference.
If the function fails, Swell retries the event. See Errors.
You can run scheduled tasks at a later date in response to record data. Swell uses this capability natively to schedule invoices, payments, cart abandonment, and many other platform tasks. Use the model.schedule property to indicate the future date for a scheduled task.
export const config: SwellConfig = {
description: 'Capture a custom scheduled payment',
model: {
events: ['payment.created', 'payment.updated'],
conditions: {
// in this example, 'date_capture_scheduled' is an App-defined field
date_capture_scheduled: { $exists: true },
},
schedule: {
// formula evaluated in context of the record
// this will cause your function to be called on the date in the field
// updates any time the field 'date_capture_scheduled' is set or changed
formula: 'date_capture_scheduled',
}
},
};
export default function (req: SwellRequest) {
const { swell, data, session, store } = req;
...
}
Instead of using a record field to indicate the date to execute your function, you can use a simple Cron schedule. Functions executed by a Cron schedule do not have any particular record context.
export const config: SwellConfig = {
description: 'Update product popularity on a daily basis',
cron: {
schedule: '0 0 * * *' // call this function every day at midnight
}
};
export default function (req: SwellRequest) {
const { swell, data, session, store } = req;
...
}
To run a cron function only when the app is ready for it, add cron.conditions. It's a filter like a model trigger's conditions, checked before each scheduled run against the app's settings as $settings and the environment as $env (live or test). When it doesn't match, the run is skipped, with no invocation or log, and the next one is checked as usual.
export const config: SwellConfig = {
description: 'Sync orders to the warehouse every hour',
cron: {
schedule: '0 * * * *',
// run only once the merchant has connected the warehouse
conditions: {
$settings: {
connection: { enabled: true },
api_key: { $exists: true },
},
},
},
};- conditions is optional, and so is each of $settings and $env in it. Use $settings to wait until the merchant has set the app up, such as connected an account or entered an API key. Use $env to limit a job to one environment: { $env: 'live' } keeps a sync with a real external service out of the test environment, and { $env: 'test' } keeps a job that resets test data out of live.
- $formula isn't supported, since a cron run has no record to evaluate it against. A push with one is refused.
- A cron function never runs while its app is inactive in the store, with or without conditions.
- If Swell can't read the app's settings, the run goes ahead.
- Removing cron from a function's config stops its schedule when you push.
To send a request to an external service on a schedule instead, use a scheduled webhook. See Webhooks.
Functions can also be exposed as custom API endpoints by exporting one or more route handler methods, get, put, post, or delete. These functions are deployed to an edge network for optimal end-user performance.
By default, you must pass an API secret key to invoke the function from an external server, or set the route.public property to indicate the function should be publicly accessible without a key.
export const config: SwellConfig = {
description: 'Retrieve subscription analytics',
route: {
methods: ['get'], // any of get, put, post, or delete
headers: ['x-webhook-signature'], // forward only these request headers
cache: {
timeout: 5000, // cache the output for 5 seconds
},
public: false // true to allow requests without a secret key
}
};
export async function get (req: SwellRequest) {
const { swell } = req;
return await swell.get('/subscriptions', {
aggregate: [
// ... aggregation pipeline
],
});
}
In this example, a GET request to https://<secret_key>@<store_id>.swell.store/functions/<app-id>/analyze-subscriptions will trigger the analyze-subscriptions.js function and return the result.
Route functions are also served through the store gateway at https://<store-id>.swell.store/functions/<app-id>/<function-name>. External requests to this URL must include an app API key in the Authorization header. The key identifies both the app and the target environment — a test key routes the request to the Test environment, and a live key to the Live environment. Without a valid key, the gateway cannot resolve the app and responds with a 404 error.
Note that query string parameters sent through the gateway arrive in req.data when the request has no body. To handle both direct and gateway invocations consistently, read parameters from both req.query and req.data.
You can call a function with the Backend API by sending PUT /:functions/app.<app-id>.<function-name> with a $call object. <app-id> is the app's id from swell.json, or its Swell ID. The response is the function's response. From another function of the same app:
const result = await req.swell.put(`/:functions/app.${req.appId}.sync-orders`, {
$call: { method: 'post', data: { order_id: orderId } },
});| Property | Description |
| data | Request body passed to the function as req.data. |
| method | HTTP method used to call the function. Defaults to post. |
| headers | Request headers passed to the function. |
| query | Query string passed to the function as req.query. |
An app can call its own functions this way without functions permissions, as long as the request body contains only $call. Calling another app's functions requires write permission on functions. Workflows and action functions can't be called with $call, and return workflow_not_callable and action_not_callable. A disabled function returns function_disabled.
An app's UI components can call its route functions with their fetch prop, at /functions/<app-id>/<function-name> on the component's own domain. These requests don't need an API key or route.public, and their responses aren't cached. Functions without a route can't be called this way.
The function receives the caller in req.swellContext, which is null for requests that don't carry a context signed by Swell:
| Property | Description |
| appId | The app's id. |
| installationId | Id of the app's installation in the store. |
| storeId | Id of the store. |
| storeUser | The admin user the component runs for, as { storeId, userId }, or null. |
| surface | Where the call comes from: admin for components in the Swell dashboard, storefront for a component block on a storefront and for a storefront app's calls for a shopper. |
| storefrontId | Id of the storefront, when surface is storefront. |
The platform verifies the context's signature, app, and store before it calls the function. Check surface and storeUser before doing anything only a store user may do:
export const config: SwellConfig = {
description: 'Palette for the BrandColor component',
route: {
methods: ['get'],
},
};
export default async function (req: SwellRequest) {
const context = req.swellContext;
// Only for store users, through one of this app's components
if (context?.surface !== 'admin' || !context.storeUser) {
throw new SwellError('Forbidden', { status: 403 });
}
return { palette: ['#111827', '#2563eb', '#f59e0b'] };
}
Functions receive req.swellContext when they're pushed with Swell CLI 2.9.27 or later. A route with this check answers other requests, such as swell api calls, with 403, so test it through the component in the dashboard.
A storefront app can call another app's functions for a shopper, as Wave does for data sources and actions. Those calls carry a storefront context: surface is storefront and storefrontId names the storefront. The context proves that the call came through one of the store's storefronts, not who the shopper is. Only req.session.account_id identifies the signed-in customer, so check that the records a function returns or changes belong to that account. See Storefront extensions.
Functions can run from buttons and menu items in the Swell dashboard. Set action: true to let the app's actions run the function when an admin user clicks them. Action functions only run from the dashboard, and cannot be called through the API or the function gateway.
export const config: SwellConfig = {
description: 'Send a product to the warehouse',
action: true,
};
export default async function (req: SwellRequest) {
const { swell, data } = req;
const { record_id } = data.$action;
...
return { message: 'Sent to the warehouse' };
}
The function receives the action context in req.data.$action, and can return { message } to show a message to the admin user. See Actions for where actions appear and how to declare them.
A function must only specify one of the following trigger types: model, route, cron, or action, but not more than one.
The following table outlines functions available for use within Swell App development.
| Property | Description |
| description | A brief description of the function. |
| kind | Type of the function: function or workflow. Defaults to function. A workflow's config accepts only description and action. See Workflows. |
| extension | ID of the swell.json extension the function implements. Events of an extension run only the functions of that extension. Workflows can't set it. |
| model | Configure this function to be called by model events. |
| model.events | An array of model events, for example [”product.updated”]. |
| model.conditions | Optional object with operators to filter function invocation based on specific properties in a request. |
| model.sequence | Optional number to indicate priority among other App triggers for the same model events. A lower number is considered higher priority. |
| model.schedule | Optional schedule. |
| model.schedule.formula | A specific field or formula to derive the scheduled task date from. |
| route | External route configuration. |
| route.public | Optionally indicate this function should be accessible without an API key. |
| route.methods | Optional array of methods to allow the function to be called by. |
| route.headers | Optional array of request header names the store gateway forwards to the function. Defaults to all headers. |
| route.cache | Configure the cache behavior for get requests to the function. |
| route.cache.timeout | Number of milliseconds to cache the result of a get request. Defaults to 5000. |
| cron | Configure this function to be called by a Cron schedule. |
| cron.schedule | A string describing a Cron schedule to invoke this function independently of an model event or external request. |
| action | Set to true to run this function from app actions in the Swell dashboard. |
| timeout | Number of milliseconds Swell waits for the function to respond, from 1000 to 20000. Defaults to 10000. Values above 10000 require the functions.long_timeout feature for the store. Applies to routes, model events, cron schedules and actions. Workflows can't set it. |
A function receives a SwellRequest. Besides req.data, req.query, req.swell and req.swellContext, described above, it has these properties:
| Property | Description |
| app | The app's addresses in the environment of the request: admin_url, the app's page in the dashboard, and frontend_url, the address of the app's installation, where its frontend and components are served. |
| environmentId | ID of the environment the function runs in: test in the Test environment, null in Live. |
| rawBody | The request body as text. On a route called through the store gateway, it's the exact body the caller sent, so you can verify a webhook signature against it. Form-encoded bodies, swell api calls and model events arrive as JSON. |
| isLocalDev | Indicates whether the function runs on your machine under swell app dev. |
| appSecrets | Your app's secrets, set with swell app secret set, by name. Empty under swell app dev. See App secrets. |
| oauth | OAuth through Swell: start() begins a connection, and callback holds the provider's answer on the call Swell makes to your callback function. See OAuth. |
Functions get rawBody when they're pushed with Swell CLI 2.6.0 or later, app with 2.9.29 or later, and environmentId with 2.9.30 or later.
Your app's own credentials reach functions as req.appSecrets (see App secrets), and OAuth connections go through req.oauth (see OAuth). Functions get both when they're pushed with Swell CLI 2.9.43 or later.
req.swell.transaction() writes up to 10 records atomically with POST /:transaction. Each operation is an object with method (post, put or delete), url and data. If any operation fails, none of the writes are saved. It resolves with an array of the operations' results, in order.
const [order] = await req.swell.transaction([
{ method: 'put', url: `/orders/${orderId}`, data: { $app: { [req.appId]: { synced: true } } } },
{ method: 'post', url: `/apps/${req.appId}/sync-log`, data: { order_id: orderId } },
]);A failed transaction throws a SwellError whose code is one of the following:
- transaction_conflict: Another write changed the same records. Safe to retry.
- transaction_throttled: The store has too many transactions in progress. Safe to retry.
- transaction_timeout: An operation or the commit took too long.
- transaction_op_failed: An operation was refused, for example by validation. err.body.error.op_index is the index of that operation.
- transaction_error: The request was invalid, for example more than 10 operations or a get operation, or the database failed.
To retry conflicts and throttling automatically, pass { retry: true } as the second argument. The function then retries up to 3 times with an increasing delay.
Writes in a transaction don't run before: or after: hook functions of any app, and don't create created, updated or deleted events. A transaction that succeeds creates one transaction.committed event that lists its operations. A transaction counts as one request plus one per operation against the store's rate limit. Workflows can't use transactions.
An app that declares permissions in swell.json must include write_:transaction to use transactions. Each operation is still checked against the app's other permissions.
Transactions need Swell CLI 2.9.0 or later.
A function can add a note to the activity timeline of an order, subscription or invoice, for example to record that it sent the order to another system. To add a note, post to /:notes with the record's id in record_id, its collection in model, and the text in body. If the app declares permissions in swell.json, they must include write_:notes.
export const config: SwellConfig = {
description: 'Send new orders to the warehouse',
model: {
events: ['order.created'],
},
};
export default async function (req: SwellRequest) {
const order = req.data;
// Send the order to the warehouse
await req.swell.post('/:notes', {
record_id: order.id,
model: 'orders',
body: 'Sent to the warehouse',
});
}Swell sets the note's app_id to the ID of the app that created it. An app_id in the request is ignored, and updating the note doesn't change it. In the new Swell dashboard, the timeline shows the note with the app's name and icon. The classic dashboard shows the note's text without an author. Notes are internal and are never shown to the customer. See Notes in the Backend API reference.
To respond with an error, throw a SwellError. The response has the error's status, which defaults to 500, and a body of { error: message }. Requests that req.swell makes throw a SwellError when the API responds with an error, with the response's status, and its error code in code.
If the function doesn't catch an error from req.swell, the response has the API's status and error body, for example the field errors of a write that failed validation.
throw new SwellError('Order not found', { status: 404 });When a function triggered by a model event fails, Swell retries the event on the same schedule as webhooks. See Webhooks for the schedule. A function can change this for the event it was called with:
- To stop retrying the event, throw a SwellError with retry: false, or respond with status 410. The failure is logged, and doesn't count toward disabling the function.
- To retry later than the schedule, throw a SwellError with retryAfter set to a number of seconds. Swell retries the event at that time or at its next scheduled retry, whichever is later, and at most 12 hours later.
throw new SwellError('Rate limited by the warehouse API', { status: 429, retryAfter: 600 });These options only affect model event triggers, including scheduled runs. Event hooks, cron schedules, routes and actions aren't retried. On a route, retryAfter sets the Retry-After header of the response.
retry needs Swell CLI 2.9.1 or later, and retryAfter 2.9.32 or later.
Like a webhook, a function whose events keep failing for 4 days is disabled. In the new Swell dashboard, the Installed apps page marks an app whose functions are failing or disabled. The app's page lists those functions, with the date a failing function will be disabled, and a Turn back on button for a disabled one, which also retries the events it missed. The app's page also shows how many of the app's workflow runs failed in the last 7 days.
Function architecture is meant to simplify your app code by deeply integrating with Swell and leveraging the Cloudflare Worker platform to the greatest extent possible.
Workflows are durable, multi-step background functions that persist across restarts and support long-duration pauses. A workflow breaks its logic into retriable steps using step.do() and can pause with step.sleep() without consuming execution time. Use them for multi-step background work that needs to survive failure between steps — syncing to an external system, extended fulfillment operations, scheduled follow-ups, imports, and batch jobs that exceed normal function timeouts.
A workflow is a function file whose config sets kind: 'workflow'. Besides description, the only key a workflow config accepts is action. Workflows can't declare route, model, cron, extension, or timeout, so a route, a model event, or a cron schedule can't start them. They're started from another function, or by an app action.
The config must be a static object literal — spreads, computed keys, and imported constants are rejected. The file must have exactly one default export, and it must be a class declared in the same file with an instance method named run. The class is constructed with no arguments.
export const config = {
kind: 'workflow',
description: 'Sync an order to the warehouse',
};
export default class SyncOrder {
async run(req: SwellWorkflowRequest, step: SwellWorkflowStep) {
const order = await step.do('load order', async () => {
return req.swell.get(`/orders/${req.data.order_id}`);
});
await step.sleep('cool off', '30 seconds');
await step.do('mark synced', async () => {
return req.swell.put(`/orders/${order.id}`, {
$app: { [req.appId]: { synced: true } },
});
});
return { ok: true };
}
}
Each step.do(name, fn) executes once and its result is durably recorded, so a step that already completed isn't re-run when the workflow retries. Keep side effects inside steps and return values that survive serialization; anything you do between steps runs again on every retry.
Use step.sleep(name, duration) to pause for a relative duration, either a string like '30 seconds' or a number of milliseconds, and step.sleepUntil(name, date) to pause until a specific time, given as a Date, an ISO string, or a timestamp. A sleeping workflow isn't running, so long pauses don't consume execution time.
An optional second argument tunes retry behavior for a single step. Within retries, limit and delay are both required, and backoff accepts 'constant', 'linear', or 'exponential'. When an API call inside a step fails with a non-retryable error, the step stops retrying immediately rather than exhausting its limit.
await step.do(
'call warehouse',
{
retries: { limit: 3, delay: '10 seconds', backoff: 'exponential' },
timeout: '30 seconds',
},
async () => {
// ...
},
);
Start a workflow from any ordinary app function with req.swell.workflows.create(), passing the workflow's name and its parameters. It returns the new instance's id (prefixed wf_inst_) and a status of active. The call returns as soon as the instance is created — it doesn't wait for the workflow to finish. The workflow must already be deployed, or the call fails with workflow_not_deployed.
Parameters must be JSON-safe and no larger than 128 KB once serialized. Only null, finite numbers, strings, booleans, plain arrays, and plain objects are accepted — a Date, a class instance, or undefined is rejected rather than coerced, with the code workflow_params_unserializable; oversized params fail with workflow_params_too_large. Pass identifiers rather than records, and re-fetch the data you need inside the workflow.
const run = await req.swell.workflows.create('sync-order', {
order_id: id,
});
// { id: 'wf_inst_...', status: 'active' }
An app action can also start a workflow that sets action: true in its config. The run receives the action's dialog values and $action in req.data.
A workflow request is narrower than an ordinary function request. You get req.data (the parameters it was started with), req.swell.get/post/put/delete, and req.swell.settings(), which takes no argument and always returns your own app's settings. Instance metadata lives on req.workflow as workflow_id, workflow_name, workflow_instance_id, trigger, and request_id — the last being the id of the function request that started it, which is how workflow logs correlate back to the caller.
req.workflow.trigger is function when a function started the run with workflows.create(), and action when an app action started it.
Some things available elsewhere are not available here. There's no req.appValues() helper — write app-namespaced fields explicitly as { $app: { [req.appId]: { ... } } }, as in the example above. A workflow also can't start another workflow, and requests to meta endpoints are blocked: any path whose first segment begins with : is rejected with workflow_operation_blocked, with a single exception for /:batch, whose child operations are checked under the same rules.
A workflow can read and update its own app's settings with req.swell.get and req.swell.put on /settings/${req.appId}. These requests cannot include a query string, and requests for the store's settings or another app's settings are rejected with workflow_operation_blocked.
Workflows are deploy-only. They don't run under swell app dev — your other functions still do, but a workflow only runs after swell app push. The iteration loop is to push, trigger the function that starts the workflow, then inspect the result. A function running locally can still call workflows.create(), as long as the workflow it names has already been pushed.
App actions that name a workflow also start its pushed version under swell app dev.
# Scaffold a workflow function
swell create function sync-order --type workflow
# Validate the file before pushing
swell schema function functions/sync-order.ts
# Workflows only run once deployed
swell app push
# Deployed workflows, and their recent run summary
swell inspect workflows --app=.
# Recent instances, newest first (default limit 10)
swell inspect workflow-runs --app=. --status failed
# A single run in detail
swell inspect workflow-runs wf_inst_... --app=. --json
# Step-level logs, scoped to your app
swell logs --type workflow --app my-appA run can end as completed, terminated, or failed, and a failed run records whether it failed while being created or while running. There's no retry command: to re-run a failed instance you start a new one with the same parameters, so it's worth making workflows idempotent on their params. There is no dedicated termination command either — swell inspect workflow-runs wf_inst_... prints a ready-to-run swell api post command for an active run. Note that run parameters are redacted from CLI output, so if you need to see what a run received, log it yourself inside a step.
Runs also appear in the Workflows tab of the app's page in the dashboard, with their steps and errors. Users with manage access to Apps can cancel an active run there.
- An app can define at most 25 workflows.
- Instance creation is rate limited to 60 per minute per store, environment, and app. Exceeding it returns workflow_create_rate_limited, which is safe to retry.
- Parameters are capped at 128 KB of serialized JSON.
- Workflow logs are retained for 30 days.
Limits on step retries, total workflow duration, and maximum sleep length come from the underlying durable execution runtime rather than from Swell.