Functions

Write Node.js functions in JavaScript or TypeScript, connect their handlers to triggers, and run your business logic next to your data.

A function is a Node.js module. Each exported handler runs when its trigger fires: an HTTP request, a change in a bucket, a schedule, a system event, a firehose message, a gRPC call or a RabbitMQ message. Functions run on Node.js 22 in isolated worker processes managed by the API.

The function editor in the panel, with code on the left and triggers, dependencies and environment variables on the right
A function in the panel: code, triggers, dependencies and environment.

Anatomy of a function

A function has a definition and an entry file.

function/hello/schema.yaml
name: hello
description: Greets the caller
language: javascript
timeout: 10
triggers:
  default:
    type: http
    active: true
    options:
      method: Get
      path: /hello
  onPost:
    type: bucket
    active: true
    options:
      bucket: 6b0b1968a5611972c29c25f7
      type: INSERT
env_vars: []
secrets: []
function/hello/index.mjs
export default function (req, res) {
  return {message: `Hello, ${req.query.name ?? "world"}!`};
}

export function onPost(change) {
  console.log("New post created", change.documentKey);
}

The keys of triggers are the names of exported handlers. default refers to the default export.

Definition fields

FieldDescription
nameRequired. Letters, digits, _ and -. Also the folder name in a CLI project and the import name for other functions.
descriptionShown in the panel.
languageRequired. javascript (entry file index.mjs) or typescript (entry file index.ts).
timeoutRequired. Seconds an event may run before it is aborted. Capped by the API's --function-timeout.
triggersHandlers and the events that call them. See Triggers.
env_vars, secretsIds of the environment variables and secrets the function can read.
warmWorkersWorkers kept ready to skip cold starts. Default 0. See Runtime.
concurrencyPerWorkerEvents one worker may run at the same time. Default 1.
category, orderGrouping and position in the panel.

Triggers

TypeFires onHandler receives
httpAn HTTP request to /fn-execute/<path>(req, res)
bucketInsert, update or delete through the bucket APIs(change)
databaseAny change in a database collection(change)
scheduleA cron schedule()
systemAPI lifecycle events such as READY()
firehoseWebSocket messages and connections({socket, pool}, message)
grpcA unary gRPC call(request)
rabbitmqA RabbitMQ queue or stream message(message, channel)

A trigger can be paused with active: false without removing it.

Create a function

Open Functions, click Add New Function, choose a name and language, then add triggers in the sidebar and write the code in the editor. Save deploys it.

Function API

EndpointActionPurpose
GET /functionfunction:indexList functions.
GET /function/:idfunction:showGet a function.
POST /functionfunction:createCreate a function.
PUT /function/:id, PATCH /function/:idfunction:updateChange the definition.
DELETE /function/:idfunction:deleteDelete a function.
GET /function/:id/indexfunction:showRead the source code.
POST /function/:id/indexfunction:updateReplace the source code, body {"index": "<code>"}.
GET /function/:id/dependenciesfunction:showList npm dependencies.
POST /function/:id/dependenciesfunction:updateInstall packages, body {"name": ["pkg@version"]}.
DELETE /function/:id/dependencies/:namefunction:updateUninstall a package.
GET /function/informationAvailable triggers, their option schemas and runtimes.

Calling Spica from a function

Inside a function, the devkit packages find the API automatically. You only provide credentials, usually an API key stored as a secret:

JavaScript
import * as Bucket from "@spica-devkit/bucket";

export default async function (req, res) {
  Bucket.initialize({apikey: process.env.SPICA_API_KEY});
  const posts = await Bucket.data.getAll(process.env.POSTS_BUCKET_ID, {
    queryParams: {filter: 'document.status == "published"', limit: 5}
  });
  return posts;
}

Sharing code between functions

A function can import another function as a package named @spica-fn/<name>. Install it as a dependency, then import it:

Terminal
curl -X POST https://api.example.com/api/function/<functionId>/dependencies \
  -H "Authorization: APIKEY <key>" \
  -H "Content-Type: application/json" \
  -d '{"name": ["@spica-fn/text-utils"]}'
JavaScript
import * as TextUtils from "@spica-fn/text-utils";

export default function (req) {
  return {slug: TextUtils.slugify(req.query.title ?? "")};
}

The panel's Imported Functions box does both steps for you. Keep shared helpers in functions without triggers.

Next steps