Apps
Functions in Swell are powered by Cloudflare Workers and executed at the edge for optimal performance. Functions have no cold boots, Swell functions do not require extra time to start up before executing your code. Since they are run on the edge, they are optimal for both server-side webhooks, and for serving personalized content directly to end-users.
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.
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.
The following table outlines functions available for use within Swell App development.
A function can only specify one of the following: model, webhook, route, or cron, but not more than one.
Attribute | Description |
description | A brief description of the function. |
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. |
webhook | Configure this function to be called by webhook events. |
webhook.events | An array of webhook events, for example [”order.paid”] |
route | External route configuration. |
public | Optionally indicate this function should be accessible without an API key. |
methods | Optional array of methods to allow the function to be called by. |
cache | Configure the cache behavior for get requests to the function. |
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. |
Functions can be triggered by model events, API calls, or by a Cron schedule. They provide a powerful way to execute custom logic by responding to specific platform events, or by serving as web-accessible API endpoints within your app. Functions can be made using TypeScript or plain JavaScript.
You can create a new function manually or by using the following CLI command.
swell create function
You can also create a new function within the Swell API:
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 reference.
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'],
// in this example, 'date_capture_scheduled' is an App-defined field
conditions: {
date_capture_scheduled: { $exists: true },
},
// 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
schedule: {
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',
// call this function every day at midnight
cron: {
schedule: '0 0 * * *'
}
};
export default function (req: SwellRequest) {
const { swell, data, session, store } = req;
...
}
Functions can also be exposed as custom API endpoints by exporting or one 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',
};
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.
Refer to the Swell partner team for detailed pricing information.