# Introduction > Spica is an open-source backend development engine that gives you data APIs, cloud functions, identity and access management, storage and an admin panel out of the box. Spica removes the repetitive parts of backend development. You describe your data, write the business logic that is unique to your product, and Spica takes care of the rest: REST, GraphQL and realtime APIs, authentication, authorization, file storage, background jobs and a back office for your team. It is free, open source (AGPL-3.0) and runs anywhere Docker runs, on MongoDB or PostgreSQL. _Diagram: Your apps, the admin panel and the CLI talk to the Spica API through an ingress. The API runs function workers and stores data in MongoDB or PostgreSQL, and files on local disk, Amazon S3 or Google Cloud Storage._ ## What you get - [Buckets](https://docs.spicaengine.com/buckets): Model your data with JSON schemas. Get validated REST, GraphQL and realtime APIs with filtering, relations, localization and history. - [Functions](https://docs.spicaengine.com/functions): Run Node.js code on HTTP requests, data changes, schedules, system events, gRPC calls or RabbitMQ messages. - [Authentication & access](https://docs.spicaengine.com/auth): Identities for your team, users for your product, API keys for services, policies and data rules for everyone. - [Storage](https://docs.spicaengine.com/storage): Upload and serve files from local disk, Amazon S3 or Google Cloud Storage, including resumable uploads. - [Admin panel](https://docs.spicaengine.com/panel): A back office where developers configure the backend and content editors manage data, with no extra code. - [CLI & devkit](https://docs.spicaengine.com/cli): Run Spica locally, keep resources in git, plan and apply changes from CI, and call Spica from typed SDKs. ## Two ways to use Spica ### As a backend engine 1. Model your data in [buckets](https://docs.spicaengine.com/buckets/schema). The REST API is generated immediately. 2. Protect the data with [bucket rules](https://docs.spicaengine.com/buckets/rules) and [policies](https://docs.spicaengine.com/auth/policies). 3. Add sign-up and login for your end users with [Passport users](https://docs.spicaengine.com/auth/users). 4. Put your business logic into [functions](https://docs.spicaengine.com/functions) and react to data changes with [triggers](https://docs.spicaengine.com/functions/bucket-and-database). 5. Give your business team [dashboards](https://docs.spicaengine.com/platform/dashboards) and the [admin panel](https://docs.spicaengine.com/panel). ### As a headless CMS 1. Model your content types in buckets and turn on [translations](https://docs.spicaengine.com/buckets/schema#translations) for localized fields. 2. Create [identities](https://docs.spicaengine.com/auth/identities) for your editors and give them policies that only expose content. 3. Let editors manage entries, images and files in the [panel](https://docs.spicaengine.com/panel/buckets). 4. Serve published content to your site through the [data API](https://docs.spicaengine.com/buckets/data-api) with an API key or user tokens. 5. Notify other systems with [webhooks](https://docs.spicaengine.com/platform/webhooks) and automate publishing with functions. ## How the docs are organized | Section | Read it when you want to | | ------------------------------------------------------------------ | ---------------------------------------------------------------------------------- | | [Get started](https://docs.spicaengine.com/get-started/quickstart) | Run Spica for the first time, learn the vocabulary and connect AI agents. | | [Build](https://docs.spicaengine.com/buckets) | Use the API: buckets, functions, authentication, storage and the platform modules. | | [Panel](https://docs.spicaengine.com/panel) | Learn your way around the admin panel. | | [CLI](https://docs.spicaengine.com/cli) | Run local projects and manage resources as code. | | [Devkit](https://docs.spicaengine.com/devkit) | Call Spica from functions, browsers, Node.js services and tests. | | [Self-hosting](https://docs.spicaengine.com/self-hosting) | Deploy and operate Spica with Docker or Kubernetes. | | [Recipes](https://docs.spicaengine.com/recipes) | Follow end-to-end scenarios that combine several features. | > **Tip: Using an AI assistant?** > > Connect it to your instance with the [Spica MCP server](https://docs.spicaengine.com/ai/mcp-server) so it can work with your buckets, functions and logs directly. Every page here also has a **Copy page** button, a `.md` version and an index in [`/llms.txt`](https://docs.spicaengine.com/llms.txt). See [Docs for AI agents](https://docs.spicaengine.com/ai/docs-for-agents). --- # Quickstart > Start a Spica project on your machine, create your first bucket, read data over REST and serve your first function, in about ten minutes. This guide runs Spica locally with the [Spica CLI](https://docs.spicaengine.com/cli). The CLI starts the API, the admin panel, a database and an ingress as Docker containers, so you don't install anything else. ## Before you begin You need: - [Docker](https://www.docker.com/) running on your machine. - [Node.js](https://nodejs.org/) 20 or newer, to install the CLI. 1. **Install the CLI** ```bash npm install -g @spica/cli spica --version ``` 2. **Start a project** Choose a name for your project and start it. The first run pulls the images, which takes a minute. **MongoDB** ```bash spica project start my-app ``` **PostgreSQL** ```bash spica project start my-app --database-type postgresql ``` When the project is ready, the CLI prints where it is serving: ```text Spica my-app is serving on http://localhost:4500. Open your browser on http://localhost:4500/dashboard to login. Identitifer: spica Password: spica ``` The panel is served at `http://localhost:4500` and the API at `http://localhost:4500/api`. If port 4500 is busy, the CLI picks a free port and tells you which one. 3. **Log in to the panel** Open `http://localhost:4500` and log in with the identifier `spica` and the password `spica`. ![The Spica panel login page with identifier and password fields](https://docs.spicaengine.com/screenshots/panel/login.webp) 4. **Create a bucket** Buckets hold your data. In the panel, open **Buckets**, click **New Bucket** and create a `Posts` bucket with a `title` (string) and a `body` (textarea) property. Then add a few entries with **New Entry**. You can do the same over the API. First get a token: ```bash curl -X POST http://localhost:4500/api/passport/identify \ -H "Content-Type: application/json" \ -d '{"identifier": "spica", "password": "spica"}' ``` ```json {"scheme": "IDENTITY", "token": "eyJhbGciOi...", "issuer": "passport/identity"} ``` Then create the bucket with that token: ```bash curl -X POST http://localhost:4500/api/bucket \ -H "Authorization: IDENTITY " \ -H "Content-Type: application/json" \ -d '{ "title": "Posts", "description": "Blog posts", "primary": "title", "properties": { "title": {"type": "string", "title": "Title"}, "body": {"type": "textarea", "title": "Body"} } }' ``` 5. **Read and write data** Use the bucket id from the response to insert and list entries: ```bash curl -X POST http://localhost:4500/api/bucket//data \ -H "Authorization: IDENTITY " \ -H "Content-Type: application/json" \ -d '{"title": "Hello Spica", "body": "My first post"}' curl "http://localhost:4500/api/bucket//data?limit=10" \ -H "Authorization: IDENTITY " ``` ```json [{"_id": "6b0b1972a5611972c29c25fd", "title": "Hello Spica", "body": "My first post"}] ``` On PostgreSQL the bucket and its entries are identified by `id` instead of `_id`. See [MongoDB and PostgreSQL](https://docs.spicaengine.com/self-hosting/databases). 6. **Write a function** Open **Functions**, click **Add New Function**, name it `hello` and add an **HTTP** trigger with method `Get` and path `/hello`. Replace the code with: ```javascript title="index.mjs" export default function (req, res) { const name = req.query.name ?? "world"; return {message: `Hello, ${name}!`}; } ``` Save, then call it: ```bash curl "http://localhost:4500/api/fn-execute/hello?name=Ada" ``` ```json {"message": "Hello, Ada!"} ``` ## Clean up Stop and remove the project when you are done. Data is kept in Docker volumes unless you ask the CLI to remove them: ```bash spica project remove my-app --retain-volumes=false ``` ## Next steps - [Core concepts](https://docs.spicaengine.com/get-started/core-concepts): Learn the vocabulary: buckets, functions, identities, users, policies and API keys. - [Design your schema](https://docs.spicaengine.com/buckets/schema): Every property type, validation option and setting a bucket supports. - [Keep resources in git](https://docs.spicaengine.com/cli/resources-as-code): Fetch your buckets and functions into files, review changes with spica plan and apply them. - [Build a blog backend](https://docs.spicaengine.com/recipes/headless-cms-blog): A complete scenario: content model, public read access, editors and webhooks. --- # Core concepts > The building blocks of a Spica project and how they fit together, from buckets and functions to identities, users, policies and API keys. ## Buckets A **bucket** is a collection of documents described by a JSON schema, like a table with a typed structure. Each bucket gets its own REST endpoints, an optional GraphQL schema and a realtime WebSocket stream. Bucket properties can be strings, numbers, dates, files, locations, relations to other buckets, hashed or encrypted values and more. Read more in [Buckets](https://docs.spicaengine.com/buckets). ## Functions A **function** is a Node.js module you write in JavaScript or TypeScript. Each exported handler is connected to a **trigger**: an HTTP route, a bucket or database change, a schedule, a system event, a firehose message, a gRPC call or a RabbitMQ message. Functions can install npm packages, read environment variables and secrets, and call Spica through the [devkit](https://docs.spicaengine.com/devkit). Read more in [Functions](https://docs.spicaengine.com/functions). ## Identities and users Spica separates the people who **build and operate** your backend from the people who **use your product**: | | Identities | Users | | -------------- | ------------------------------ | ----------------------------------------------------- | | Who | Developers, editors, operators | Your product's end users | | Log in with | `POST /passport/identify` | `POST /passport/login` | | Token scheme | `IDENTITY` | `USER` | | Typical access | The panel and management APIs | Your data, filtered by bucket rules | | SSO | SAML | OAuth (Google, GitHub, Facebook, Okta, Auth0, custom) | Read more in [Authentication & access](https://docs.spicaengine.com/auth). ## API keys An **API key** is a long-lived credential for servers, scripts, the CLI and CI pipelines. Like identities and users, an API key only gets the permissions of the policies attached to it. ## Policies A **policy** is a named list of **statements**. Each statement allows an **action** (for example `bucket:data:index`) on a **module**, optionally limited to specific **resources** (for example a single bucket). Spica ships with read-only and full-access policies for every module, and you can write your own. Policies are attached to identities, users and API keys. Every request is checked against them. ## Bucket rules Policies decide **which endpoints** a caller may use. **Bucket rules** decide **which documents** a user may read or write. A rule is an expression such as `document.owner == auth._id`, evaluated for every document. Rules apply to `USER` requests. Identities and API keys are only checked against their policies. ## Storage objects A **storage object** is a file plus its metadata (name, content type, size). Objects can be organized into folders by their names, referenced from bucket properties of type `storage`, and stored on local disk, Amazon S3 or Google Cloud Storage. ## Environment variables and secrets **Environment variables** and **secrets** are key/value pairs that you attach to functions. Both appear in `process.env`. Secrets are encrypted at rest and their values are never returned by the API. ## Resources as code Buckets, functions, policies, environment variables and secrets can be exported into a folder of YAML and code files with the CLI, reviewed in pull requests, and applied to any instance with `spica plan` and `spica apply`. Read more in [Resources as code](https://docs.spicaengine.com/cli/resources-as-code). ## How a request flows 1. The client sends a request with an `Authorization` header: `IDENTITY `, `USER ` or `APIKEY `. 2. Spica authenticates the caller and loads the policies attached to it. 3. The policies must allow the action on the resource, otherwise the response is `403 Forbidden`. 4. For bucket data requests made with a `USER` token, the bucket's read or write rule filters or rejects documents. 5. The request is executed, the activity is recorded, and change events are sent to realtime subscribers, bucket triggers and webhooks. --- # How Spica runs > The processes and services that make up a Spica deployment, what each one is responsible for and how requests travel between them. A Spica deployment is a small set of services. Understanding them makes it easier to run Spica locally, size it for production and debug it. _Diagram: Your apps, the admin panel and the CLI reach the Spica API through an ingress that routes / to the panel and /api to the API. The API runs function workers and stores data in MongoDB or PostgreSQL and files in local disk, S3 or Google Cloud Storage._ ## The pieces | Component | Image | Responsibility | | ---------------- | --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | API | `spicaengine/api` | Every module: buckets, functions, passport, storage, dashboards, webhooks, activity, config and status. Listens on one HTTP port and, for gRPC triggers, on port `50051`. | | Panel | `spicaengine/panel` | The admin panel, a static web app served by nginx. It calls the API at `/api` on the same origin. | | Database | `mongo` or `spicaengine/postgres` | Stores everything. MongoDB must run as a replica set because Spica relies on change streams. | | Ingress | nginx or your Kubernetes ingress | Routes `/` to the panel and `/api` to the API, and terminates TLS. | | Function workers | Child processes of the API | Run your function code in isolated Node.js processes. | | Object storage | Local disk, S3 or GCS | Holds uploaded files when you use the storage module. | ## Request path Clients only talk to the ingress. A typical production setup serves the panel and the API from the same host: ```text https://admin.example.com/ → panel https://admin.example.com/api/ → API (the --public-url of the API) ``` The API's `--public-url` must be the URL that clients use to reach it, including the `/api` suffix when you serve it under a path. Spica uses it to build storage object URLs, OAuth redirect URLs and magic links. ## Function workers The API schedules function events onto **workers**: Node.js processes that load your function's code and run the handler that matches the trigger. - Each function gets its own workers, so a crashing or slow function doesn't affect others. - Workers are started on demand. A function can keep some workers **warm** to skip the cold start. - A worker can run several events of the same function at once when you raise the function's `concurrencyPerWorker`. - Every event has a **timeout**. When it is reached, the event is aborted. See [Runtime and scaling](https://docs.spicaengine.com/functions/runtime) for the settings that control workers. ## Realtime and change streams Realtime bucket streams, bucket triggers, database triggers and webhooks are all driven by database change events. On MongoDB they come from change streams, which is why MongoDB has to run as a replica set, even with a single node. ## Running more than one API replica You can run several API replicas behind a load balancer. Turn on `--replication` so that the replicas coordinate work, and make sure every replica can reach the same function assets and storage files. Use a shared volume or the S3/GCS strategies. The [Helm chart](https://docs.spicaengine.com/self-hosting/kubernetes) does this for you when `application.replicas` is greater than one. ## Where data lives | Data | Location | | ---------------------------------------------------------------- | ------------------------------------------------------------------------- | | Buckets, documents, identities, users, policies, functions, logs | The database | | Function source and installed packages | `--persistent-path` or the function asset storage (local path, S3 or GCS) | | Uploaded files | `--persistent-path/storage`, S3 or GCS | | Logs, activity and status records | The database, expired after `--common-log-lifespan` | --- # MCP server > Connect Claude, Cursor, VS Code and other AI agents to a Spica instance with @spica/mcp, so they can manage buckets, data, functions, access and storage. [`@spica/mcp`](https://github.com/spica-engine/spica-mcp-server) is a [Model Context Protocol](https://modelcontextprotocol.io) server for Spica. It gives an AI agent tools to work with your instance: design buckets, query and import data, write and deploy functions, read logs, manage API keys and policies, and organize storage. The server runs on your machine and talks to the Spica API with an API key, so the agent can do exactly what that key's [policies](https://docs.spicaengine.com/auth/policies) allow. ## Requirements - Node.js 22 or newer. - A Spica instance (MongoDB or PostgreSQL) and its API URL, including `/api`. - An [API key](https://docs.spicaengine.com/auth/api-keys) with the policies the agent needs. ## Create an API key for the agent Create a dedicated key so you can limit and revoke the agent's access independently of everything else. In the panel, open **Access → API Keys**, create a key named after the agent, and attach policies. Or use the API: ```bash curl -X POST https://api.example.com/api/passport/apikey \ -H "Authorization: IDENTITY " -H "Content-Type: application/json" \ -d '{"name": "ai-agent", "description": "MCP server for Claude Code", "active": true}' curl -X PUT https://api.example.com/api/passport/apikey//policy/BucketReadOnlyAccess \ -H "Authorization: IDENTITY " ``` Start with read-only policies and add write access when you need it: | Tools | Policies | | -------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ | | `list_buckets`, `list_bucket_data`, `export_bucket_data` | `BucketReadOnlyAccess` | | `insert_bucket`, `update_bucket`, `save_bucket_data`, `import_bucket_data`, `list_bucket_data_profile` | `BucketFullAccess` | | `list_functions`, `get_function_index`, `get_function_dependencies` | `FunctionReadOnlyAccess` | | `insert_function`, `update_function`, `save_function_index`, `save_function_dependencies` | `FunctionFullAccess` | | `list_env_vars` | `EnvVarReadOnlyAccess` (included in `FunctionReadOnlyAccess`) | | `list_secrets` | `SecretReadOnlyAccess` | | `insert_env_var`, `update_env_var`, `insert_secret`, `update_secret` | `EnvVarFullAccess`, `SecretFullAccess` (both included in `FunctionFullAccess`) | | `list_storage_objects` | `StorageReadOnlyAccess` | | `insert_storage_object`, `update_storage_object`, `rename_storage_object` | `StorageFullAccess` | | `list_apikeys`, `list_identities`, `list_policies`, `list_users` | The matching `…ReadOnlyAccess` policies | | `insert_apikey`, `update_apikey`, `insert_identity`, `update_identity`, `insert_policy`, `update_policy` | The matching `…FullAccess` policies | | `list_user_profile` | `UserFullAccess` | | `list_activities` | `ActivityReadOnlyAccess` | | `list_function_logs` | Any valid key | A tool whose action the key doesn't allow returns the API's error to the agent, such as `Spica API 403: You do not have sufficient permissions to do passport:user:index on resource`, and the other tools keep working. > **Warning: API keys bypass bucket rules** > > [Bucket rules](https://docs.spicaengine.com/buckets/rules) don't apply to API keys, so a key with `BucketReadOnlyAccess` reads every document, including private user data. Use a staging instance, or scope the policies to the buckets the agent should see. ## Connect your agent The server reads two environment variables: | Variable | Value | | -------------- | ------------------------------------------------------ | | `SPICA_URL` | The API URL, for example `https://api.example.com/api` | | `SPICA_APIKEY` | The key you created | **Claude Code** ```bash claude mcp add spica \ --env SPICA_URL=https://api.example.com/api \ --env SPICA_APIKEY= \ -- npx -y @spica/mcp ``` The server is added to the current project. Add `--scope user` to use it in all your projects, or `--scope project` to write it to a `.mcp.json` file you can commit. Check the connection with `claude mcp list`, or `/mcp` in a session. **Claude Desktop** Add the server to `claude_desktop_config.json`: ```json { "mcpServers": { "spica": { "command": "npx", "args": ["-y", "@spica/mcp"], "env": { "SPICA_URL": "https://api.example.com/api", "SPICA_APIKEY": "" } } } } ``` **Cursor** Add the same `mcpServers` entry to Cursor's MCP settings (`.cursor/mcp.json` in a project, or `~/.cursor/mcp.json` for all projects): ```json { "mcpServers": { "spica": { "command": "npx", "args": ["-y", "@spica/mcp"], "env": { "SPICA_URL": "https://api.example.com/api", "SPICA_APIKEY": "" } } } } ``` **VS Code** Add the server to `.vscode/mcp.json`: ```json { "servers": { "spica": { "command": "npx", "args": ["-y", "@spica/mcp"], "env": { "SPICA_URL": "https://api.example.com/api", "SPICA_APIKEY": "" } } } } ``` To work with several instances, add one server per instance with its own name and key, for example `spica-staging` and `spica-production`. On startup the server loads the instance's function trigger options from `GET /function/information` and its database engine from `GET /status/engine`. The tool schemas follow that information, so the agent sees the trigger types, options and collections your instance supports. If `SPICA_URL` or `SPICA_APIKEY` is missing, the URL can't be reached, or the key is not valid (`Spica API 401: Unauthorized`), the server exits and your agent reports that it couldn't connect. ## Tools ### Database | Tool | Does | | -------------------- | ---------------------------------------------------------------------------------------------------------------------- | | `list_buckets` | List bucket schemas. | | `insert_bucket` | Create a bucket from a [schema](https://docs.spicaengine.com/buckets/schema). | | `update_bucket` | Replace a bucket schema. | | `list_bucket_data` | Query documents with `filter`, `sort`, `limit`, `skip`, relation resolving and a language. | | `save_bucket_data` | Insert a document, or replace it when it contains its key. | | `export_bucket_data` | Write documents to a JSON or CSV file on your machine. | | `import_bucket_data` | Insert documents from a local JSON or CSV file, in parallel batches (`concurrency`, default 50). Reports each failure. | ### Development | Tool | Does | | --------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `list_functions` | List functions with their triggers. | | `insert_function`, `update_function` | Create or replace a function, its [triggers](https://docs.spicaengine.com/functions) and its env var and secret links. | | `get_function_index`, `save_function_index` | Read or replace a function's code. TypeScript is compiled on save, and type or syntax errors come back as diagnostics with line and column. JavaScript is saved without checks. | | `get_function_dependencies`, `save_function_dependencies` | Read or install npm packages. | | `list_env_vars`, `insert_env_var`, `update_env_var` | Manage [environment variables](https://docs.spicaengine.com/platform/env-vars-and-secrets). | | `list_secrets`, `insert_secret`, `update_secret` | Manage secrets. | ### Authentication | Tool | Does | | ------------------------------------------------------- | ------------------------------------------------------------------------------------- | | `list_apikeys`, `insert_apikey`, `update_apikey` | Manage API keys and the policies attached to them. | | `list_identities`, `insert_identity`, `update_identity` | Manage [identities](https://docs.spicaengine.com/auth/identities) and their policies. | | `list_policies`, `insert_policy`, `update_policy` | Manage [policies](https://docs.spicaengine.com/auth/policies). | | `list_users` | List [users](https://docs.spicaengine.com/auth/users) with filters, sort and paging. | ### Storage, debugging and auditing | Tool | Does | | ------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | | `list_storage_objects` | List [storage](https://docs.spicaengine.com/storage) objects with filters and paging. | | `insert_storage_object`, `update_storage_object`, `rename_storage_object` | Upload base64 content, replace it, or rename an object. | | `list_function_logs` | Read [function logs](https://docs.spicaengine.com/functions/logs) by date range, function, level or text. | | `list_bucket_data_profile`, `list_user_profile` | Read the query profiler, to find slow queries and missing [indexes](https://docs.spicaengine.com/buckets/advanced#indexes). | | `list_activities` | Read the [activity](https://docs.spicaengine.com/platform/activity) log by identifier, action, resource and date. | The server has 38 tools, and none of them delete anything. Deleting buckets, documents, functions or files stays a deliberate step in the panel, the CLI or the API. A few behaviors worth knowing: - `save_bucket_data` validates against the bucket schema like the API does. `import_bucket_data` keeps going when a row fails and returns each failure, for example `Spica API 400: .price must be number,null`. - `export_bucket_data` and `import_bucket_data` read and write files on the machine that runs the MCP server. Export only uses the base name of `fileName`, so it can't write outside `directory`. - `list_secrets` returns secret names with a salt and hash, never the values. - `insert_apikey` returns the new key once, in the tool result. Treat the agent's transcript as sensitive when it creates keys. ## MongoDB and PostgreSQL The server adapts to the instance's database: | | MongoDB | PostgreSQL | | -------------- | ------------------ | ---------------------------------------------------------------------------------------------------------------- | | Record key | `_id` | `id` | | Document key | `_id` | The bucket's `primary` property | | Bucket filters | Expression or JSON | [Expression](https://docs.spicaengine.com/buckets/querying#expression-filters) only, such as `document.age > 18` | Tools accept either `_id` or `id` and return records with the engine's key. On PostgreSQL, `insert_bucket` requires `primary`, the property that becomes the primary key, usually a `uuid` with `options.generated: true`. JSON filters are rejected before they reach the API, with `JSON filters are not supported on PostgreSQL. Use an expression filter, e.g. document.age > 1.` ## What you can ask Once connected, describe the outcome and let the agent pick the tools: - "Create a `products` bucket with a title, a price, a cover image and a category relation, then add five sample products." - "Write an HTTP function `GET /orders/summary` that returns today's order count and total, and use the `STRIPE_KEY` secret." - "Why is the `onOrderPaid` function failing? Check its logs from the last hour and fix the code." - "Export all users who signed up this month to a CSV file." - "Which queries on the `orders` bucket are slow, and which indexes would help?" - "Create a read-only policy for the `articles` bucket and an API key that uses it." ## Best practices - **Point agents at staging first.** Let the agent build on a local or staging instance, then move the result to production with [resources as code](https://docs.spicaengine.com/cli/resources-as-code) and a reviewed `spica plan`. - **One key per agent and environment.** Name keys after what uses them, give them only the policies they need, and deactivate them when you're done. - **Keep keys out of shared files.** `.mcp.json` and `.vscode/mcp.json` are often committed. Commit the server entry and pass the key through your shell environment or your client's secret settings instead. - **Review what the agent changes.** Write tools take effect immediately. Check the [activity log](https://docs.spicaengine.com/platform/activity) or ask the agent to summarize what it changed. - **Give the agent the docs too.** Pair the MCP server with [Spica docs for agents](https://docs.spicaengine.com/ai/docs-for-agents) so it uses the right schema fields, filters and trigger options. --- # Docs for AI agents > Give AI coding agents accurate Spica context with Markdown pages, llms.txt and llms-full.txt, and combine them with the MCP server. Every page of these docs is also available as clean Markdown, so you can hand exactly the context an agent needs to Claude, ChatGPT, Cursor or any other tool. ## Copy a page Use **Copy page** at the top of any page to copy it as Markdown. Links become absolute, tabs become labeled sections and callouts become blockquotes, so nothing is lost when you paste it into a chat. The menu next to it can also: | Action | Use it to | | ------------------------ | ----------------------------------------------------------------- | | View as Markdown | Open the Markdown version in a new tab. | | Copy Markdown link | Copy the URL of the Markdown version, for agents that fetch URLs. | | Open in Claude / ChatGPT | Start a chat that asks the assistant to read the page. | ## Markdown URLs Add `.md` to any page URL to get its Markdown, for example [`/buckets/querying.md`](https://docs.spicaengine.com/buckets/querying.md). Agents that can fetch URLs can read pages this way without a browser. ## llms.txt | File | Contains | | -------------------------------------------------------------- | ------------------------------------------------------------------------------- | | [`/llms.txt`](https://docs.spicaengine.com/llms.txt) | An index of every page with its description and Markdown URL, by section. | | [`/llms-full.txt`](https://docs.spicaengine.com/llms-full.txt) | Every page in one file, for agents that work best with all the context at once. | Point an agent at `llms.txt` and let it pick the pages it needs. Use `llms-full.txt` when the agent has a large context window and you want it to know the whole platform. ## Tips - **Add Spica context to your project.** Put the pages your project relies on, or a link to `llms.txt`, in your agent's project instructions (for example `CLAUDE.md` or `.cursor/rules`). - **Prefer specific pages.** One or two relevant pages, such as [Querying](https://docs.spicaengine.com/buckets/querying) and [Rules](https://docs.spicaengine.com/buckets/rules), give better answers than the whole site. - **Combine docs with live access.** With the [MCP server](https://docs.spicaengine.com/ai/mcp-server), the agent can read your actual buckets and functions while the docs explain how they work. --- # Buckets > Buckets are schema-defined collections of documents with ready-made REST, GraphQL and realtime APIs, validation, rules, localization and history. A bucket is a collection of documents that share a schema. When you create a bucket, Spica immediately serves: - A **REST API** to list, read, create, replace, patch and delete documents. - A **realtime WebSocket** stream that pushes inserts, updates and deletes to subscribers. - A **GraphQL** schema, when GraphQL is enabled. - A **data entry UI** in the admin panel, generated from the schema. Every write is validated against the schema. Every read can be filtered, sorted, paginated, localized and joined with related buckets. ![The Posts bucket in the panel, showing entries in a table with title, slug, body, status and tags columns](https://docs.spicaengine.com/screenshots/panel/bucket.webp) _A bucket in the panel_ ## A first look A bucket definition is JSON. This one describes blog posts: ```json title="Posts bucket" { "title": "Posts", "description": "Blog posts", "primary": "title", "history": true, "properties": { "title": {"type": "string", "title": "Title", "options": {"translate": true}}, "slug": {"type": "string", "title": "Slug", "pattern": "^[a-z0-9-]+$"}, "status": {"type": "string", "title": "Status", "enum": ["draft", "published"], "default": "draft"}, "author": {"type": "relation", "title": "Author", "bucketId": "", "relationType": "onetoone"}, "created_at": {"type": "date", "title": "Created at", "default": ":created_at", "readOnly": true} }, "required": ["title", "slug"], "acl": {"read": "document.status == \"published\"", "write": "false == true"} } ``` And this is how an app reads published posts with their authors, in Turkish: ```bash curl "https://api.example.com/api/bucket//data?relation=author&limit=10" \ -H "Authorization: USER " \ -H "Accept-Language: tr_TR" ``` ## In this section - [Schema & property types](https://docs.spicaengine.com/buckets/schema): Every property type, validation keyword and bucket setting. - [Data API](https://docs.spicaengine.com/buckets/data-api): Create, read, replace, patch and delete documents over REST. - [Querying](https://docs.spicaengine.com/buckets/querying): Filters, sorting, pagination, relations and localization. - [Rules](https://docs.spicaengine.com/buckets/rules): Decide which documents and fields each user can read or write. - [Realtime](https://docs.spicaengine.com/buckets/realtime): Subscribe to live query results over WebSocket. - [History](https://docs.spicaengine.com/buckets/history): Keep the previous versions of documents and inspect them. - [GraphQL](https://docs.spicaengine.com/buckets/graphql): Query and mutate bucket data with GraphQL. - [Indexes, limits & performance](https://docs.spicaengine.com/buckets/advanced): Indexes, document limits, caching, hashed and encrypted fields. ## Who can access bucket data Access is checked in two layers: 1. **Policies** decide whether the caller may use an endpoint on a bucket at all, for example `bucket:data:index` on the `Posts` bucket. 2. **Rules** decide which documents a `USER` may read or write. Identities and API keys skip rules. See [Rules](https://docs.spicaengine.com/buckets/rules) and [Policies](https://docs.spicaengine.com/auth/policies). --- # Schema & property types > Define a bucket's properties, validation, defaults, relations and translations, and every bucket-level setting. A bucket's schema is a JSON Schema document with a few Spica-specific keywords. You can edit it in the panel, over the API (`POST /bucket`, `PUT /bucket/:id`, `PATCH /bucket/:id`) or as YAML with the [CLI](https://docs.spicaengine.com/cli/resources-as-code). ## Bucket settings | Field | Type | Description | | ------------------ | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | | `title` | string, 4–100 chars | **Required.** Name shown in the panel and used by the CLI as the folder name. | | `description` | string, 5–250 chars | **Required.** Shown under the title in the panel. | | `properties` | object | **Required.** The properties of a document, at least one. | | `primary` | string | The property that represents a document, for example in relation pickers. On PostgreSQL it is also the [primary key](#primary-keys-on-postgresql). | | `required` | string\[] | Properties that every document must have. | | `icon` | string | Material icon name shown in the panel. Default `view_stream`. | | `category` | string | Groups buckets in the panel sidebar. | | `order` | number | Position of the bucket in the panel. | | `readOnly` | boolean | Documents can't be edited from the panel's data pages. | | `history` | boolean | Keep the [previous versions](https://docs.spicaengine.com/buckets/history) of each document. Default `false`. | | `acl` | `{read, write}` | [Rules](https://docs.spicaengine.com/buckets/rules) evaluated for `USER` requests. Default `true==true` for both. | | `indexes` | array | Database [indexes](https://docs.spicaengine.com/buckets/advanced#indexes) for the bucket. | | `documentSettings` | object | `countLimit` and `limitExceedBehaviour` (`prevent` or `remove`). See [Document limits](https://docs.spicaengine.com/buckets/advanced#document-limits). | Property names must start with a letter or `_`, contain only letters, digits and `_`, and can't be `_id`. ## Property types | Type | Stored as | Panel input | Notes | | ------------- | ------------- | ---------------- | -------------------------------------------------------------------------------- | | `string` | string | Text field | Supports `enum`, `pattern`, `minLength`, `maxLength`. | | `textarea` | string | Multi-line text | | | `richtext` | string (HTML) | Rich text editor | | | `number` | number | Number field | Supports `minimum`, `maximum`, `enum`. | | `boolean` | boolean | Toggle | | | `date` | date | Date-time picker | Send ISO 8601 strings. Supports the `:created_at` and `:updated_at` defaults. | | `color` | string | Color picker | Hex color such as `#36369c`. | | `array` | array | List editor | Describe the items with `items`. Supports `minItems`, `maxItems`, `uniqueItems`. | | `multiselect` | array | Multi select | An array of values chosen from `items.enum`. | | `object` | object | Nested form | Describe the fields with `properties` and `required`. | | `json` | any JSON | JSON editor | No inner validation. | | `storage` | string (URL) | File picker | Stores the URL of a [storage object](https://docs.spicaengine.com/storage). | | `relation` | id or id\[] | Document picker | References documents in another bucket. See [Relations](#relations). | | `location` | GeoJSON Point | Map picker | `{"type": "Point", "coordinates": [longitude, latitude]}` | | `hash` | string | Text field | Stored as a one-way keyed hash. Can be matched in filters but never read back. | | `encrypted` | object | Text field | Encrypted at rest, decrypted in responses. | | `uuid` | string | Text field | PostgreSQL only. | | `integer` | integer | Number field | PostgreSQL only. | | `bigint` | string | Number field | PostgreSQL only. Returned as a string to keep its precision. | You can ask an instance which types it supports: ```bash curl https://api.example.com/api/bucket/capabilities -H "Authorization: APIKEY " ``` ```json {"propertyTypes": ["array", "multiselect", "boolean", "number", "object", "string", "storage", "richtext", "date", "textarea", "color", "relation", "location", "json", "hash", "encrypted"]} ``` ## Common property keywords Every property accepts these keywords in addition to `type`: | Keyword | Description | | ---------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | | `title` | Label shown in the panel. | | `description` | Help text shown in the panel. | | `default` | Value used when the property is missing on insert. | | `readOnly` | The value isn't editable in the panel. Combined with `default`, the server always writes the default and ignores the value the client sends. | | `enum` | Allowed values. | | `pattern` | Regular expression a string must match. | | `minLength`, `maxLength` | String length limits. | | `minimum`, `maximum` | Number limits. | | `items`, `minItems`, `maxItems`, `uniqueItems` | Array item schema and limits. | | `properties`, `required` | Fields of an `object` property. | | `options.translate` | Store one value per language. See [Translations](#translations). | | `acl` | A field-level rule. See [Field rules](https://docs.spicaengine.com/buckets/rules#field-rules). | ### Example ```json { "slug": { "type": "string", "title": "Slug", "description": "URL-safe identifier", "pattern": "^[a-z0-9-]+$" }, "status": { "type": "string", "title": "Status", "enum": ["draft", "published"], "default": "draft" }, "tags": { "type": "array", "title": "Tags", "items": {"type": "string"}, "maxItems": 10, "uniqueItems": true }, "views": {"type": "number", "title": "Views", "minimum": 0, "default": 0} } ``` A document that breaks the schema is rejected with `400`: ```json {"message": ".slug must match pattern \"^[a-z0-9-]+$\"", "error": "validation failed", "statusCode": 400} ``` ## Server-set dates Use the predefined defaults to let Spica fill in dates: | Default | Value | | ------------- | ----------------------------------- | | `:created_at` | The time of the write that sets it. | | `:updated_at` | The time of the write that sets it. | ```json { "created_at": {"type": "date", "title": "Created at", "default": ":created_at", "readOnly": true}, "updated_at": {"type": "date", "title": "Updated at", "default": ":updated_at"} } ``` Defaults are applied on insert and on replace (`PUT`), not on patch (`PATCH`). Two consequences: - With `readOnly`, `created_at` is written again on every `PUT`. Update documents with `PATCH` when you want to keep the original creation time. - `updated_at` is only refreshed by `PUT`. If you patch documents and need a reliable modification time, set it yourself or from a [bucket trigger](https://docs.spicaengine.com/functions/bucket-and-database). `GET /bucket/predefineddefaults` lists the available defaults. ## Relations A `relation` property stores references to documents in another bucket: ```json { "author": { "type": "relation", "title": "Author", "bucketId": "", "relationType": "onetoone", "dependent": false } } ``` | Field | Description | | -------------- | ----------------------------------------------------------------------------------------------------------------- | | `bucketId` | **Required.** The referenced bucket. | | `relationType` | **Required.** `onetoone` stores a single id, `onetomany` stores an array of ids. | | `dependent` | When `true`, deleting a document also deletes the documents it references through this property. Default `false`. | Write relations as ids, and use the `relation` query parameter to [resolve them](https://docs.spicaengine.com/buckets/querying#relations) when you read. ## Translations Set `options.translate` to store one value per language: ```json {"title": {"type": "string", "title": "Title", "options": {"translate": true}}} ``` Write all languages as an object keyed by locale: ```json {"title": {"en_US": "Hello Spica", "tr_TR": "Merhaba Spica"}} ``` When you read, Spica returns the value in the language of the `Accept-Language` header and falls back to the default language. The available and default languages are stored in the bucket preferences: ```bash curl https://api.example.com/api/preference/bucket -H "Authorization: IDENTITY " ``` ```json {"scope": "bucket", "language": {"available": {"tr_TR": "Turkish", "en_US": "English"}, "default": "en_US"}} ``` Change them with `PUT /preference/bucket` or in the panel. See [Localization](https://docs.spicaengine.com/buckets/querying#localization) for reading options. ## Locations A `location` property stores a GeoJSON point. Coordinates are `[longitude, latitude]`: ```json {"location": {"type": "Point", "coordinates": [28.97, 41.01]}} ``` Add a `2dsphere` [index](https://docs.spicaengine.com/buckets/advanced#indexes) when you filter by distance. ## Hashed and encrypted properties Both types protect sensitive values. They need the `bucket-data-hash-secret` and `bucket-data-encryption-secret` API options, which are derived from the master key when you don't set them. | | `hash` | `encrypted` | | -------------------- | ------------------------------------- | ------------------------------------------------- | | Stored | A keyed hash (HMAC) | Ciphertext plus a hash | | Returned | The hash | The original value | | Filter with equality | Yes, send the plain value | Yes, send the plain value | | Use for | National ids, values you only compare | Phone numbers, addresses, values you must display | ```json { "national_id": {"type": "hash", "title": "National ID"}, "phone": {"type": "encrypted", "title": "Phone"} } ``` > **Warning** > > Changing the hash or encryption secret makes existing values unreadable. Keep them, or the master key they are derived from, stable for the life of the instance. ## Primary keys on PostgreSQL On PostgreSQL, `primary` names the bucket's primary key, and documents are identified by that property instead of `_id`. The primary property must be of type `uuid`, `integer`, `bigint` or `string`, can't be translated, and can set `options.generated` to let the database create values: ```json { "title": "Authors", "description": "People who write posts", "primary": "id", "properties": { "id": {"type": "uuid", "title": "ID", "options": {"generated": true}}, "name": {"type": "string", "title": "Name"} } } ``` Only the primary property can be generated. More differences between the engines are listed in [MongoDB and PostgreSQL](https://docs.spicaengine.com/self-hosting/databases). ## Changing a schema You can change a bucket at any time. Keep in mind: - New required properties and stricter validation only apply to documents you write from now on. - Removing a property doesn't remove existing values from stored documents. - Changing a property's type can make old values fail validation on the next write. - Deleting a bucket deletes all of its documents and history. Review schema changes before they reach production with [`spica plan`](https://docs.spicaengine.com/cli/resources-as-code). --- # Data API > Create, read, replace, patch and delete bucket documents over REST, with the permissions each endpoint needs and the responses it returns. Every bucket has a REST API under `/bucket/:bucketId/data`. All examples use `https://api.example.com/api` as the public URL of the API. ## Authentication Send one of these headers with every request: ```http Authorization: IDENTITY Authorization: USER Authorization: APIKEY ``` The caller's policies must allow the endpoint's **action** on the bucket. For `USER` requests the bucket's [rules](https://docs.spicaengine.com/buckets/rules) are also applied. | Endpoint | Action | | ------------------------------------------- | -------------------- | | `GET /bucket/:bucketId/data` | `bucket:data:index` | | `GET /bucket/:bucketId/data/:documentId` | `bucket:data:show` | | `POST /bucket/:bucketId/data` | `bucket:data:create` | | `PUT /bucket/:bucketId/data/:documentId` | `bucket:data:update` | | `PATCH /bucket/:bucketId/data/:documentId` | `bucket:data:update` | | `DELETE /bucket/:bucketId/data/:documentId` | `bucket:data:delete` | ## List documents `GET /bucket/:bucketId/data` ```bash curl "https://api.example.com/api/bucket//data?limit=2&sort=%7B%22views%22%3A-1%7D" \ -H "Authorization: APIKEY " ``` ```json [ { "_id": "6b0b1972a5611972c29c25fd", "title": "Hello Spica", "slug": "hello-spica", "status": "published", "tags": ["intro", "news"], "author": "6b0b1972a5611972c29c25fb", "views": 42, "created_at": "2026-11-28T18:12:02.224Z" } ] ``` | Query parameter | Description | | --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `filter` | An [expression](https://docs.spicaengine.com/buckets/querying#expression-filters) or a [JSON filter](https://docs.spicaengine.com/buckets/querying#json-filters). | | `sort` | JSON object of property names and `1` (ascending) or `-1` (descending), for example `{"views":-1}`. | | `limit` | Maximum number of documents to return. | | `skip` | Number of documents to skip. | | `paginate` | When `true`, the response is `{"meta": {"total": n}, "data": [...]}`. | | `relation` | `true` to resolve every relation, or property paths such as `author` to resolve some. | | `localize` | Default `true`. Set to `false` to receive every language of translated properties. | The `Accept-Language` header selects the language of translated properties, and the response's `Content-Language` header tells you which language was used. See [Querying](https://docs.spicaengine.com/buckets/querying) for details. ## Get a document `GET /bucket/:bucketId/data/:documentId` Accepts `relation` and `localize` like the list endpoint. When a read rule hides the document from a user, the response is empty. ```bash curl https://api.example.com/api/bucket//data/6b0b1972a5611972c29c25fd?relation=author \ -H "Authorization: APIKEY " ``` ## Insert a document `POST /bucket/:bucketId/data` The body is validated against the bucket schema. Defaults are applied and the stored document is returned: ```bash curl -X POST https://api.example.com/api/bucket//data \ -H "Authorization: APIKEY " \ -H "Content-Type: application/json" \ -d '{ "title": {"en_US": "Hello Spica", "tr_TR": "Merhaba Spica"}, "slug": "hello-spica", "status": "published", "author": "6b0b1972a5611972c29c25fb" }' ``` ```json { "title": {"en_US": "Hello Spica", "tr_TR": "Merhaba Spica"}, "slug": "hello-spica", "status": "published", "author": "6b0b1972a5611972c29c25fb", "views": 0, "created_at": "2026-11-28T18:12:02.224Z", "_id": "6b0b1972a5611972c29c25fd" } ``` ## Replace a document `PUT /bucket/:bucketId/data/:documentId` Replaces the whole document. Properties you leave out are removed, and defaults are applied again. Returns the new document. ## Patch a document `PATCH /bucket/:bucketId/data/:documentId` Applies a [JSON merge patch](https://www.rfc-editor.org/rfc/rfc7396). Properties you send are changed, properties set to `null` are removed, and everything else is kept. Returns the updated document. ```bash curl -X PATCH https://api.example.com/api/bucket//data/6b0b1972a5611972c29c25fd \ -H "Authorization: APIKEY " \ -H "Content-Type: application/merge-patch+json" \ -d '{"views": 43, "cover": null}' ``` > **Tip** > > Prefer `PATCH` for partial updates. It doesn't overwrite properties that someone else changed in the meantime, and it keeps server-set values such as `created_at`. ## Delete a document `DELETE /bucket/:bucketId/data/:documentId` Returns `204 No Content`. When a relation property is marked `dependent`, the referenced documents are deleted too. ## Several operations in one request Combine several requests into one round trip with the [batch endpoint](https://docs.spicaengine.com/platform/batch): ```json { "requests": [ {"id": "1", "method": "POST", "url": "bucket//data", "body": {"title": {"en_US": "One"}, "slug": "one"}, "headers": {"Authorization": "APIKEY "}}, {"id": "2", "method": "POST", "url": "bucket//data", "body": {"title": {"en_US": "Two"}, "slug": "two"}, "headers": {"Authorization": "APIKEY "}} ] } ``` ## Errors | Status | When | Example message | | ------ | ---------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------- | | `400` | The document doesn't match the schema, or a unique index is violated. | `.slug must match pattern "^[a-z0-9-]+$"` | | `401` | The `Authorization` header is missing or invalid, or a write rule rejects the operation. | `No auth token`, `ACL rules has rejected this operation.` | | `403` | A policy denies the operation. | `You do not have sufficient permissions to do bucket:data:index on resource ` | | `404` | The bucket or document doesn't exist. | `Could not find the schema with id ` | ## Engine differences On **PostgreSQL**: - Documents are identified by the bucket's [primary property](https://docs.spicaengine.com/buckets/schema#primary-keys-on-postgresql) instead of `_id`. Use its value as `:documentId`. - `bigint` values are returned as strings. - Filters must be [expressions](https://docs.spicaengine.com/buckets/querying#expression-filters). JSON filters are rejected. See [MongoDB and PostgreSQL](https://docs.spicaengine.com/self-hosting/databases) for the full list. ## From code The [bucket devkit](https://docs.spicaengine.com/devkit/bucket) wraps these endpoints: ```typescript import * as Bucket from "@spica-devkit/bucket"; Bucket.initialize({apikey: process.env.API_KEY, publicUrl: "https://api.example.com/api"}); const posts = await Bucket.data.getAll(POSTS_BUCKET_ID, { queryParams: {filter: 'document.status == "published"', sort: {created_at: -1}, limit: 10} }); ``` --- # Querying > Filter, sort, paginate, resolve relations and localize bucket data with expression and JSON filters. Queries are sent as query parameters of `GET /bucket/:bucketId/data`. The same filters work in [realtime streams](https://docs.spicaengine.com/buckets/realtime) and in the [devkit](https://docs.spicaengine.com/devkit/bucket). > **Note** > > Remember to URL-encode filter values. With `curl`, use `-G --data-urlencode 'filter=...'` as in the examples below. ## Expression filters An expression filter is a boolean expression over the document. It works on both MongoDB and PostgreSQL, and uses the same language as [rules](https://docs.spicaengine.com/buckets/rules). ```bash curl -G https://api.example.com/api/bucket//data \ -H "Authorization: APIKEY " \ --data-urlencode 'filter=document.status == "published" && document.views > 10' ``` Refer to properties through `document`, for example `document.title`, `document.author.name` or `document.tags`. Simple comparisons also accept the bare property name (`views > 10`), but functions and relations require the `document.` prefix, so it is a good habit to always use it. ### Operators | Operator | Example | | ----------------------- | ------------------------------------------------------- | | `==`, `!=` | `document.status == "draft"` | | `<`, `<=`, `>`, `>=` | `document.views >= 100` | | `&&`, `\|\|` | `document.status == "published" && document.views > 10` | | `in` | `document.status in ["draft", "review"]` | | `+`, `-`, `*`, `/`, `%` | `document.price * document.quantity > 1000` | ### Functions | Function | True when | | ----------------------------------------- | ------------------------------------------------------------------------------ | | `has(document.cover)` | The property exists. | | `some(document.tags, ["news", "intro"])` | The array contains at least one of the values. | | `every(document.tags, ["news", "intro"])` | The array contains all of the values. | | `equal(document.tags, ["intro", "news"])` | The array has exactly these values. | | `regex(document.slug, "^hello", "i")` | The string matches the pattern. The third argument holds regex flags. | | `startsWith(document.slug, "hel")` | The string starts with the text. | | `contains(document.slug, "spica")` | The string contains the text. | | `length(document.tags) == 2` | Returns the length of an array or string, for comparisons. | | `unixTime(document.published_at) < now()` | `unixTime` converts a date to seconds, `now()` is the current time in seconds. | ```text some(document.tags, ["news"]) && unixTime(document.published_at) > now() - 7 * 24 * 60 * 60 ``` ### Filtering through relations Expressions can follow relations. Spica joins the related bucket for you: ```text document.author.name == "Ada Lovelace" ``` ### Hashed and encrypted properties Compare a `hash` or `encrypted` property with the plain value. Spica hashes it before matching: ```text document.national_id == "12345678901" ``` ## JSON filters On **MongoDB** you can also send a JSON filter with MongoDB query operators: ```bash curl -G https://api.example.com/api/bucket//data \ -H "Authorization: APIKEY " \ --data-urlencode 'filter={"status": "published", "views": {"$gte": 10}, "tags": {"$in": ["news"]}}' ``` - Dates can be written as ISO strings: `{"published_at": {"$gte": "2026-11-01T00:00:00Z"}}`. - `_id` and relation values can be written as strings. - Dot paths go through relations: `{"author.name": "Ada Lovelace"}`. - Translated properties are matched in the requested language. - `$near` isn't allowed because results are counted. Use `$geoWithin` for geographic filters. > **Warning** > > PostgreSQL doesn't accept JSON filters and responds with `A json filter is not supported on PostgreSQL. Use a expression filter.` Use expressions if you want your code to work on both engines. ## Sorting `sort` is a JSON object. Use `1` for ascending and `-1` for descending order: ```text sort={"published_at": -1, "title": 1} ``` ## Pagination Use `limit` and `skip`, and set `paginate=true` to get the total count with the page: ```bash curl "https://api.example.com/api/bucket//data?paginate=true&limit=20&skip=40" \ -H "Authorization: APIKEY " ``` ```json {"meta": {"total": 87}, "data": [{"_id": "...", "title": "..."}]} ``` > **Tip** > > Counting has a cost on large buckets. Only send `paginate=true` when you display the total, and always set a `limit`. ## Relations Relations are returned as ids by default. Ask Spica to resolve them with `relation`: | Value | Result | | ------------------------- | -------------------------------------------------------------- | | `relation=true` | Resolve every relation of the bucket. | | `relation=author` | Resolve one relation. Repeat the parameter to resolve several. | | `relation=author.company` | Resolve a nested relation through a resolved one. | ```bash curl "https://api.example.com/api/bucket//data?relation=author&limit=1" \ -H "Authorization: APIKEY " ``` ```json [ { "_id": "6b0b1972a5611972c29c25fd", "title": "Hello Spica", "author": { "_id": "6b0b1972a5611972c29c25fb", "name": "Ada Lovelace", "email": "ada@example.com" } } ] ``` Resolving relations makes queries slower, so only resolve what the client renders. ## Localization For properties with `options.translate`, the response contains one language: 1. The language in the `Accept-Language` header, when the bucket preferences list it. 2. Otherwise the default language from the bucket preferences. ```bash curl "https://api.example.com/api/bucket//data?limit=1" \ -H "Authorization: APIKEY " \ -H "Accept-Language: tr_TR" -i ``` ```http HTTP/1.1 200 OK Content-Language: tr_TR [{"_id": "6b0b1972a5611972c29c25fd", "title": "Merhaba Spica", "body": "

İlk yazı

"}] ``` Send `localize=false` to receive every language, for example to build an editor: ```json [{"_id": "6b0b1972a5611972c29c25fd", "title": {"en_US": "Hello Spica", "tr_TR": "Merhaba Spica"}}] ``` ## Query profiling Identities and API keys can inspect how queries perform with `GET /bucket/:bucketId/data/profile`, which returns the database's profiler entries for the bucket. The panel shows the same data under **Observability**. --- # Rules > Use read and write rules to control which documents each end user can see and change, and field rules to hide individual properties. Rules are expressions stored on the bucket, in its `acl` field. They let you implement row-level security for your end users, for example "users can only read their own orders" or "only published posts are public". ```json { "acl": { "read": "document.status == \"published\" || document.owner == auth._id", "write": "document.owner == auth._id" } } ``` ## When rules run | Caller | Policies checked | Rules applied | | ---------------- | ---------------- | ------------- | | `USER` token | Yes | Yes | | `IDENTITY` token | Yes | No | | `APIKEY` | Yes | No | Rules are an additional layer for end users. A user still needs a [policy](https://docs.spicaengine.com/auth/policies) that allows the endpoint, such as `bucket:data:index` for the bucket. Identities and API keys see and write every document their policies allow. > **Warning: API keys bypass rules** > > Never ship an API key with write access to a browser or mobile app. Use user tokens for client apps, and keep API keys on servers and in functions. ## Read rules The read rule is evaluated for every document a user lists, reads or receives over [realtime](https://docs.spicaengine.com/buckets/realtime). Documents for which it evaluates to `false` are left out of the result. ```text document.status == "published" ``` ## Write rules The write rule is evaluated for inserts, replaces, patches and deletes made by users. When it evaluates to `false`, the request fails with status `401` and the message `ACL rules has rejected this operation.` The rule sees the document as it will be stored. ```text document.owner == auth._id ``` To make a bucket read-only for users, deny all writes: ```text false == true ``` ## Available variables | Variable | Contents | | ---------- | ------------------------------------------------------------------------------------------------------- | | `document` | The document being read or written. Relations can be followed, for example `document.project.owner`. | | `auth` | The authenticated user: `_id`, `username`, `policies`, `lastLogin` and other fields of the user record. | On PostgreSQL the user's id is `auth.id`. The rule language is the same as [expression filters](https://docs.spicaengine.com/buckets/querying#expression-filters), including functions such as `some`, `has` and `regex`. ## Examples ### Users see their own documents ```json { "acl": { "read": "document.owner == auth._id", "write": "document.owner == auth._id" } } ``` Set `owner` from a function or validate it with the write rule so users can't create documents for someone else. ### Public content with drafts ```json { "acl": { "read": "document.status == \"published\"", "write": "false == true" } } ``` Editors work with identities in the panel, which ignore rules. Users only ever see published entries. ### Team membership through a relation ```json { "acl": { "read": "some(document.project.members, [auth._id])", "write": "document.project.owner == auth._id" } } ``` ## Field rules A property can have its own `acl` expression. When it evaluates to `false` for a user, the property is removed from that user's read responses: ```json { "email": { "type": "string", "title": "Email", "acl": "document._id == auth._id" } } ``` ## Testing rules 1. Create a test user and attach a policy that allows the data endpoints of the bucket. 2. Log in as that user with `POST /passport/login`. 3. Call the data API with `Authorization: USER ` and check what comes back. ```bash curl -X POST https://api.example.com/api/passport/login \ -H "Content-Type: application/json" \ -d '{"username": "reader1", "password": "readerPass1"}' curl https://api.example.com/api/bucket//data \ -H "Authorization: USER " ``` > **Tip** > > Rules that touch relations need extra lookups on every query. Keep frequently checked values, such as `owner`, directly on the document. --- # Realtime > Subscribe to bucket data over WebSocket, receive inserts, updates and deletes as they happen, and write documents through the same connection. Every bucket has a WebSocket endpoint that streams the result of a query and keeps it up to date. Use it for live feeds, dashboards, chat and collaborative screens. ## Connect ```text wss://api.example.com/api/bucket//data?Authorization=&filter=...&sort=...&limit=...&skip=... ``` | Query parameter | Description | | --------------- | ------------------------------------------------------------------------------------------------------------------------ | | `Authorization` | URL-encoded credentials, for example `USER eyJhbGci...` or `APIKEY abc123`. | | `filter` | An [expression](https://docs.spicaengine.com/buckets/querying#expression-filters) (on MongoDB a JSON filter also works). | | `sort` | JSON sort object, for example `{"created_at":-1}`. | | `limit`, `skip` | Window of documents to keep in the stream. | The caller needs the `bucket:data:stream` action on the bucket. For users, the bucket's read rule is applied to every message. ## Messages from the server Every message is a JSON object with a `kind`: | `kind` | Name | Payload | | ------ | -------------- | ---------------------------------------------------------- | | `0` | Initial | `document`: one document of the current result. | | `1` | End of initial | The initial result has been sent. | | `2` | Insert | `document`: a document that entered the result. | | `3` | Delete | `document`: a document that left the result. | | `4` | Expunge | `document`: a document removed because the window changed. | | `5` | Update | `document`: the new version of a document. | | `6` | Replace | `document`: a replaced document. | | `7` | Order | The order of documents changed. | | `8` | Response | `status` and `message`: the reply to a message you sent. | | `-1` | Error | `status` and `message`. | ```json {"kind": 0, "document": {"_id": "6b0b1972a5611972c29c25fd", "title": {"en_US": "Hello Spica"}, "views": 42}} {"kind": 1} {"kind": 5, "document": {"_id": "6b0b1972a5611972c29c25fd", "title": {"en_US": "Hello Spica"}, "views": 43}} ``` > **Note** > > Realtime documents aren't localized: translated properties arrive with every language. Pick the language on the client. ## Writing through the connection Send `{"event": ..., "data": ...}` to insert, replace, patch or delete documents. Each message is answered with a `kind: 8` response: | `event` | `data` | Response | | --------- | -------------------------------- | ---------------- | | `insert` | The new document | `201 Created` | | `replace` | The full document with `_id` | `200 OK` | | `patch` | `_id` and the changed properties | `204 No Content` | | `delete` | `{"_id": "..."}` | `204 No Content` | ```json {"event": "patch", "data": {"_id": "6b0b1972a5611972c29c25fd", "views": 45}} ``` ```json {"kind": 8, "status": 204, "message": "No Content"} ``` Writes made this way go through the same validation, policies and rules as REST writes. ## Example: a live list in the browser ```javascript const url = new URL(`wss://api.example.com/api/bucket/${BUCKET_ID}/data`); url.searchParams.set("Authorization", `USER ${token}`); url.searchParams.set("filter", 'document.status == "published"'); url.searchParams.set("sort", JSON.stringify({created_at: -1})); url.searchParams.set("limit", "20"); const posts = new Map(); const socket = new WebSocket(url); socket.onmessage = event => { const message = JSON.parse(event.data); switch (message.kind) { case 0: // initial case 2: // insert case 5: // update case 6: // replace posts.set(message.document._id, message.document); break; case 3: // delete case 4: // expunge posts.delete(message.document._id); break; case 1: // end of initial render([...posts.values()]); return; } render([...posts.values()]); }; ``` The [bucket devkit](https://docs.spicaengine.com/devkit/bucket#realtime) does this bookkeeping for you and returns an RxJS observable of the current result: ```typescript import * as Bucket from "@spica-devkit/bucket"; Bucket.initialize({user: token, publicUrl: "https://api.example.com/api"}); const connection = Bucket.data.realtime.getAll(BUCKET_ID, { filter: 'document.status == "published"', sort: {created_at: -1}, limit: 20 }); const subscription = connection.subscribe(posts => render(posts)); connection.patch({_id: postId, views: 45}); ``` ## Tips - Keep `limit` small. The server tracks the window for every connection. - Reconnect when the socket closes. The devkit retries automatically on abnormal closures. - Use realtime for screens that change while users look at them. For one-off reads, REST is simpler and can be [cached](https://docs.spicaengine.com/buckets/advanced#response-cache). --- # History > Keep previous versions of bucket documents, list them and see how a document looked at any point. When a bucket has `"history": true`, Spica records what changed every time a document is replaced or patched. You can list the changes of a document and reconstruct how it looked at a given point, which is useful for audits and for restoring content an editor overwrote. History is a server feature that is on by default. Turn it off for the whole instance with `--bucket-history=false`. ## Enable history on a bucket ```json { "title": "Posts", "description": "Blog posts", "history": true, "properties": {} } ``` ## List the changes of a document `GET /bucket/:bucketId/history/:documentId` Returns one entry per change, newest first. `changes` is the number of properties that changed: ```json [ {"_id": "6b0b19ada5611972c29c2609", "date": "2026-11-28T18:13:01.000Z", "changes": 1}, {"_id": "6b0b19aca5611972c29c2608", "date": "2026-11-28T18:13:00.000Z", "changes": 1} ] ``` ## See a previous version `GET /bucket/:bucketId/history/:documentId/:historyId` Returns the document as it was at that point of its history. It doesn't modify the stored document. To restore it, send the returned document back with `PUT /bucket/:bucketId/data/:documentId`. ## Clear the history of a bucket `DELETE /bucket/:bucketId/history` Deletes every history entry of the bucket and returns `204`. ## Permissions | Endpoint | Action | | ------------- | -------------------- | | List and show | `bucket:data:index` | | Clear | `bucket:data:delete` | History endpoints accept identities and API keys. ## Limits - Spica keeps the **last 10 changes** of each document. Older entries are removed as new ones arrive. - Inserts and deletes aren't recorded. Use the [activity stream](https://docs.spicaengine.com/platform/activity) to see who created or deleted documents. - When you remove a property from the schema or change its type, its recorded changes are dropped. ![The entry editor of the Posts bucket, with fields for title, slug, rich text body, status, tags, author relation and cover image](https://docs.spicaengine.com/screenshots/panel/bucket-entry.webp) _Editors can browse the history of an entry from the panel._ --- # GraphQL > Turn on the GraphQL endpoint to query and mutate bucket data with a schema generated from your buckets. Spica can generate a GraphQL schema from your buckets. Every bucket gets query and mutation fields, and the schema is rebuilt when buckets change. > **Note** > > GraphQL is available on MongoDB instances. On PostgreSQL the module isn't started, even when the flag is on. ## Enable GraphQL GraphQL is off by default. Start the API with: ```bash --bucket-graphql=true ``` The endpoint is `POST /graphql` under your public URL, for example `https://api.example.com/api/graphql`. Opening it in a browser shows GraphiQL. ## Generated types Each bucket becomes a type named `Bucket_` with these operations: | Operation | Field | | --------- | ------------------------------------------------------------------------------------------------------------ | | List | `FindBucket_(limit: Int, skip: Int, sort: JSON, language: String, query: JSON): Bucket_FindResponse` | | Get | `FindByBucket_Id(_id: ObjectId!, language: String): Bucket_` | | Insert | `insertBucket_(input: Bucket_Input): Bucket_` | | Replace | `replaceBucket_(_id: ObjectId!, input: Bucket_Input): Bucket_` | | Patch | `patchBucket_(_id: ObjectId!, input: JSON): Bucket_` | | Delete | `deleteBucket_(_id: ObjectId!): String` | List results have the shape `{meta {total} data {...}}`. Relations are exposed as nested types, so you can select fields of related documents in one query. ## Example ```graphql query RecentPosts { FindBucket_6b0b1968a5611972c29c25f7(limit: 5, sort: {created_at: -1}, language: "en_US") { meta { total } data { _id title slug author { name } } } } ``` ```bash curl -X POST https://api.example.com/api/graphql \ -H "Authorization: APIKEY " \ -H "Content-Type: application/json" \ -d '{"query": "{ FindBucket_6b0b1968a5611972c29c25f7(limit: 5) { data { _id title } } }"}' ``` ## Authorization The caller needs the `bucket:index` action to load the schema, plus the data actions of each bucket it touches, like the REST API. ## When to use it - Use GraphQL when clients need to fetch nested data with precise field selection. - Use the REST API when you need expression filters that work on every engine, or for the simplest integration. - Property names that aren't valid GraphQL names are adjusted, and the endpoint lists such adjustments in a `Warning` response header. --- # Indexes, limits & performance > Add database indexes, cap the number of documents, cache responses and keep bucket queries fast. ## Indexes Declare indexes in the bucket's `indexes` array. Spica creates them in the database when you save the bucket and drops the ones you remove. ```json { "indexes": [ {"definition": {"slug": 1}, "options": {"unique": true}}, {"definition": {"status": 1, "published_at": -1}}, {"definition": {"location": "2dsphere"}} ] } ``` | Field | Description | | ------------ | -------------------------------------------------------------------------------------------------- | | `definition` | Property paths and their direction: `1` ascending, `-1` descending, or `"2dsphere"` for locations. | | `options` | Index options. `unique` rejects duplicate values. | A duplicate value is rejected with `400`: ```json {"statusCode": 400, "message": "Value of the property .slug should unique across all documents."} ``` **Engine differences.** On MongoDB, `options` accepts any MongoDB index option, such as `sparse`, `expireAfterSeconds` or `partialFilterExpression`. On PostgreSQL, `options` accepts only `unique`, `sparse` and `background`, and a `2dsphere` index must have a single property and can't be unique. ### Which indexes to add - Properties you filter on frequently, such as `status`, `owner` or a foreign key. - Properties you sort on, combined with the filter properties in the same index. - Properties that must be unique, such as a `slug` or an external id. - Properties used in [rules](https://docs.spicaengine.com/buckets/rules), because rules run on every user query. Use **Observability** in the panel or `GET /bucket/:bucketId/data/profile` to find slow queries. ## Document limits Cap the number of documents in a bucket with `documentSettings`: ```json { "documentSettings": { "countLimit": 1000, "limitExceedBehaviour": "remove" } } ``` | `limitExceedBehaviour` | When the limit is reached | | ---------------------- | ---------------------------------------------------------- | | `prevent` | New inserts are rejected. | | `remove` | The insert is accepted and the oldest document is deleted. | This is useful for logs, notifications and caches that should only keep recent entries. On PostgreSQL, `remove` isn't available when the primary key is a `string`, because string keys have no insertion order. To cap the total number of documents across all buckets, start the API with `--bucket-data-limit=`. ## Response cache The API can cache `GET` responses of bucket data in memory: ```bash --bucket-cache=true --bucket-cache-ttl=60 ``` - Cached responses are served for `--bucket-cache-ttl` seconds (default `60`). - Writes through the API invalidate the cache of the bucket. - `DELETE /bucket/cache` clears all cached responses. Turn it on for read-heavy public content. Leave it off when documents are changed directly in the database or when every read must reflect the latest write. ## Hooks When `--bucket-hooks` is on (the default), functions can react to inserts, updates and deletes on buckets with the [bucket trigger](https://docs.spicaengine.com/functions/bucket-and-database). Turn it off with `--bucket-hooks=false` if you don't use bucket triggers. ## Performance checklist - Always send a `limit`, and only use `paginate=true` when you show the total. - Resolve only the relations the client renders. - Put values that rules check directly on the document instead of behind relations. - Index the properties you filter, sort and rule on. - Prefer `PATCH` for small updates. - Use [realtime](https://docs.spicaengine.com/buckets/realtime) only for screens that need live updates. --- # 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](https://docs.spicaengine.com/screenshots/panel/function.webp) _A function in the panel: code, triggers, dependencies and environment._ ## Anatomy of a function A function has a definition and an entry file. ```yaml title="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: [] ``` ```javascript title="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 | Field | Description | | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `name` | **Required.** Letters, digits, `_` and `-`. Also the folder name in a CLI project and the import name for [other functions](#sharing-code-between-functions). | | `description` | Shown in the panel. | | `language` | **Required.** `javascript` (entry file `index.mjs`) or `typescript` (entry file `index.ts`). | | `timeout` | **Required.** Seconds an event may run before it is aborted. Capped by the API's `--function-timeout`. | | `triggers` | Handlers and the events that call them. See [Triggers](#triggers). | | `env_vars`, `secrets` | Ids of the [environment variables and secrets](https://docs.spicaengine.com/functions/environment) the function can read. | | `warmWorkers` | Workers kept ready to skip cold starts. Default `0`. See [Runtime](https://docs.spicaengine.com/functions/runtime). | | `concurrencyPerWorker` | Events one worker may run at the same time. Default `1`. | | `category`, `order` | Grouping and position in the panel. | ## Triggers | Type | Fires on | Handler receives | | ----------------------------------------------------------------------------------------- | ------------------------------------------------ | --------------------------- | | [`http`](https://docs.spicaengine.com/functions/http) | An HTTP request to `/fn-execute/` | `(req, res)` | | [`bucket`](https://docs.spicaengine.com/functions/bucket-and-database) | Insert, update or delete through the bucket APIs | `(change)` | | [`database`](https://docs.spicaengine.com/functions/bucket-and-database#database-trigger) | Any change in a database collection | `(change)` | | [`schedule`](https://docs.spicaengine.com/functions/schedule) | A cron schedule | `()` | | [`system`](https://docs.spicaengine.com/functions/other-triggers#system) | API lifecycle events such as `READY` | `()` | | [`firehose`](https://docs.spicaengine.com/functions/other-triggers#firehose) | WebSocket messages and connections | `({socket, pool}, message)` | | [`grpc`](https://docs.spicaengine.com/functions/other-triggers#grpc) | A unary gRPC call | `(request)` | | [`rabbitmq`](https://docs.spicaengine.com/functions/other-triggers#rabbitmq) | A RabbitMQ queue or stream message | `(message, channel)` | A trigger can be paused with `active: false` without removing it. ## Create a function **Panel** 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. **CLI** Create `function//schema.yaml` and `function//index.mjs` (or `index.ts`) in your project folder, then run: ```bash spica plan spica apply ``` See [Resources as code](https://docs.spicaengine.com/cli/resources-as-code). **REST API** ```bash curl -X POST https://api.example.com/api/function \ -H "Authorization: APIKEY " \ -H "Content-Type: application/json" \ -d '{ "name": "hello", "language": "javascript", "timeout": 10, "triggers": {"default": {"type": "http", "active": true, "options": {"method": "Get", "path": "/hello"}}} }' curl -X POST https://api.example.com/api/function//index \ -H "Authorization: APIKEY " \ -H "Content-Type: application/json" \ -d '{"index": "export default function () { return {ok: true}; }"}' ``` ## Function API | Endpoint | Action | Purpose | | ------------------------------------------ | ----------------- | ------------------------------------------------------ | | `GET /function` | `function:index` | List functions. | | `GET /function/:id` | `function:show` | Get a function. | | `POST /function` | `function:create` | Create a function. | | `PUT /function/:id`, `PATCH /function/:id` | `function:update` | Change the definition. | | `DELETE /function/:id` | `function:delete` | Delete a function. | | `GET /function/:id/index` | `function:show` | Read the source code. | | `POST /function/:id/index` | `function:update` | Replace the source code, body `{"index": ""}`. | | `GET /function/:id/dependencies` | `function:show` | List npm dependencies. | | `POST /function/:id/dependencies` | `function:update` | Install packages, body `{"name": ["pkg@version"]}`. | | `DELETE /function/:id/dependencies/:name` | `function:update` | Uninstall a package. | | `GET /function/information` | | Available triggers, their option schemas and runtimes. | ## Calling Spica from a function Inside a function, the [devkit](https://docs.spicaengine.com/devkit) packages find the API automatically. You only provide credentials, usually an API key stored as a [secret](https://docs.spicaengine.com/functions/environment): ```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/`. Install it as a dependency, then import it: ```bash curl -X POST https://api.example.com/api/function//dependencies \ -H "Authorization: APIKEY " \ -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 - [HTTP functions](https://docs.spicaengine.com/functions/http): Build REST endpoints, webhooks receivers and streaming responses. - [React to data changes](https://docs.spicaengine.com/functions/bucket-and-database): Run code when documents are inserted, updated or deleted. - [Dependencies & builds](https://docs.spicaengine.com/functions/dependencies): Install npm packages and choose how code is built. - [Best practices](https://docs.spicaengine.com/functions/best-practices): Keep functions fast, safe and easy to operate. --- # HTTP functions > Serve HTTP endpoints from functions, with routing, CORS, authentication, authorization and per-IP rate limiting. The `http` trigger turns a handler into an HTTP endpoint under `/fn-execute`: ```text https://api.example.com/api/fn-execute/ ``` ## Options | Option | Default | Description | | -------------- | ------- | ---------------------------------------------------------------------------------------------- | | `method` | `Get` | `Get`, `Post`, `Put`, `Patch`, `Delete`, `Head` or `All`. | | `path` | `/` | Route path. Supports parameters such as `/books/:id`. | | `preflight` | `true` | Answer CORS preflight (`OPTIONS`) requests for this route using the API's CORS settings. | | `authenticate` | `[]` | Strategies allowed to call the route: any of `IDENTITY`, `APIKEY`, `USER`. Empty means public. | | `authorize` | `false` | Also check the caller's policies. Requires at least one `authenticate` strategy. | | `rateLimit` | | `{limit, ttl}`: at most `limit` requests per IP within `ttl` milliseconds. | ```yaml triggers: getBook: type: http active: true options: method: Get path: /books/:id authenticate: [USER, APIKEY] rateLimit: limit: 60 ttl: 60000 ``` ## The request ```javascript export function getBook(req, res) { req.method; // "GET" req.path; // "/books/42" req.params.id; // "42" req.query.lang; // "en" req.headers.get("user-agent"); // headers are a Map with lower-case keys req.get("authorization"); // shortcut for headers.get req.cookies.get("session"); // cookies are a Map req.body; // parsed from JSON or form bodies req.ip; // client address } ``` ## The response Return a value to send it. Objects and arrays become JSON, strings become `text/html`, and `Buffer`s are sent as `application/octet-stream`: ```javascript export default async function (req) { return {ok: true}; } ``` Use `res` for status codes, headers and streaming: ```javascript export async function createBook(req, res) { if (!req.body?.title) { return res.status(400).send({message: "title is required"}); } const book = await saveBook(req.body); res.headers.set("Location", `/books/${book._id}`); return res.status(201).send(book); } ``` | Method | Description | | ----------------------------------------------------------------- | -------------------------------------- | | `res.status(code, message?)` | Set the status code. Chainable. | | `res.send(body)` | Send a body and end the response. | | `res.json(body)` | Send a JSON body and end the response. | | `res.headers.set(name, value)`, `res.headers.append(name, value)` | Set response headers before sending. | | `res.writeHead(status, message?, headers?)` | Start a streamed response. | | `res.write(chunk, encoding?)` | Write a chunk. | | `res.end(chunk?, encoding?)` | Finish the response. | When the handler throws or its promise rejects before a response is sent, the client receives `500`: ```json {"statusCode": 500, "error": "Internal Server Error", "message": "Error: database unreachable"} ``` ### Streaming ```javascript export async function events(req, res) { await res.writeHead(200, "OK", {"Content-Type": "text/event-stream", "Cache-Control": "no-cache"}); for (let i = 1; i <= 3; i++) { await res.write(`data: tick ${i}\n\n`); await new Promise(resolve => setTimeout(resolve, 1000)); } await res.end(); } ``` ## Authentication and authorization With `authenticate`, Spica verifies the `Authorization` header before the function runs and rejects invalid callers with `401`. Your handler can then trust the header and read the caller from it, for example with [`Identity.verifyToken`](https://docs.spicaengine.com/devkit/identity) or [`Auth.verifyToken`](https://docs.spicaengine.com/devkit/auth). With `authorize: true`, the caller's policies are checked as well. Write policies that allow the function's route to control who may call it. ```yaml options: method: Post path: /orders authenticate: [USER] authorize: true ``` ## CORS Function routes use the API's CORS settings (`--cors-allowed-origins`, `--cors-allowed-methods`, `--cors-allowed-headers`, `--cors-allow-credentials`). Keep `preflight: true` for routes called from browsers. ## Rate limiting `rateLimit` counts requests per client IP. When the limit is reached, Spica answers `429 Too Many Requests` without running the function. Behind a proxy, make sure `--trust-proxy` is set so that Spica sees the real client IP. ## Calling a function from a client Use plain `fetch`: ```javascript const response = await fetch("https://api.example.com/api/fn-execute/books/42", { headers: {Authorization: `USER ${token}`} }); const book = await response.json(); ``` Or generate a typed client for every HTTP function with [`spica function orm`](https://docs.spicaengine.com/cli/orm#function-orm). ## Tips - Validate `req.body` yourself. Function bodies aren't validated against a schema. - Return early with `res.status(...).send(...)` for error cases, so the response is never sent twice. - Keep long work out of the request: write a job to a bucket and process it with a [bucket trigger](https://docs.spicaengine.com/functions/bucket-and-database) or a [schedule](https://docs.spicaengine.com/functions/schedule). --- # Bucket and database triggers > Run a function whenever documents are inserted, updated or deleted, either through the bucket APIs or anywhere in the database. Two triggers react to data changes: | | `bucket` | `database` | | -------- | --------------------------------------------------------------- | ----------------------------------------------------- | | Fires on | Writes made through the bucket data API, the panel and realtime | Any change in a database collection, whatever made it | | Scope | One bucket | Any collection, including system collections | | Payload | Previous and current document | Current document and changed fields | | Requires | `--bucket-hooks` (on by default) | Change streams (MongoDB replica set) | Use the **bucket** trigger for business logic around your data. Use the **database** trigger when you need to see changes that don't go through the bucket API, or changes in system collections such as identities. ## Bucket trigger ```yaml triggers: onPostCreated: type: bucket active: true options: bucket: 6b0b1968a5611972c29c25f7 type: INSERT ``` | Option | Description | | -------- | -------------------------------------- | | `bucket` | Id of the bucket to watch. | | `type` | `INSERT`, `UPDATE`, `DELETE` or `ALL`. | The handler receives a change: | Field | Description | | ------------- | -------------------------------------------------------- | | `bucket` | Id of the bucket. | | `documentKey` | Id of the document. | | `previous` | The document before the change, for updates and deletes. | | `current` | The document after the change, for inserts and updates. | | `kind` | `"update"` or `"delete"`. | ```javascript export async function onPostCreated(change) { const post = change.current; console.info("New post", change.documentKey, post.slug); } ``` > **Note** > > In the current release `kind` is left empty for inserts. Subscribe to `INSERT` with its own trigger, or treat a change without `previous` as an insert, when your handler must tell operations apart. ### Example: keep a counter up to date ```javascript import * as Bucket from "@spica-devkit/bucket"; export async function onCommentChanged(change) { Bucket.initialize({apikey: process.env.SPICA_API_KEY}); const postId = (change.current ?? change.previous).post; const comments = await Bucket.data.getAll(process.env.COMMENTS_BUCKET_ID, { queryParams: {filter: `document.post == "${postId}"`, paginate: true, limit: 1} }); await Bucket.data.patch(process.env.POSTS_BUCKET_ID, postId, {commentCount: comments.meta.total}); } ``` > **Warning: Avoid loops** > > A bucket trigger that writes to the bucket it watches fires itself again. Watch a different operation type, compare `previous` and `current` before writing, or write to another bucket. ## Database trigger ```yaml triggers: onIdentityChange: type: database active: true options: collection: identity type: INSERT ``` | Option | Description | | ------------ | -------------------------------------------------------------------------------- | | `collection` | Collection to watch. Bucket data lives in collections named `bucket_`. | | `type` | `INSERT`, `UPDATE`, `REPLACE` or `DELETE`. | The handler receives: | Field | Description | | ------------------- | -------------------------------------------------- | | `kind` | `"insert"`, `"update"`, `"replace"` or `"delete"`. | | `collection` | The collection name. | | `documentKey` | Id of the changed document. | | `document` | The current document, when it still exists. | | `updateDescription` | For updates: `updatedFields` and `removedFields`. | ```javascript export function onIdentityChange(change) { console.info(`${change.kind} on ${change.collection}`, change.documentKey); } ``` The panel lists the collections you can pick. Over the API, `GET /function/information` returns the allowed values. ## Delivery - Events are processed asynchronously after the write has been committed. The client that made the write doesn't wait for your function. - Handlers run under the function's timeout. Keep them short, or hand long work off to a queue. - Make handlers idempotent. Writing the same result twice should be harmless. --- # Scheduled functions > Run functions on a cron schedule in the time zone of your choice, for reports, cleanups, syncs and reminders. The `schedule` trigger runs a handler on a cron schedule. ```yaml triggers: nightlyReport: type: schedule active: true options: frequency: "0 3 * * *" timezone: Europe/Istanbul ``` | Option | Description | | ----------- | ----------------------------------------------------------------------------------------- | | `frequency` | **Required.** A cron expression with 5 fields, or 6 fields when the first one is seconds. | | `timezone` | **Required.** An IANA time zone such as `UTC`, `Europe/Istanbul` or `America/New_York`. | The handler receives no arguments: ```javascript export async function nightlyReport() { const report = await buildReport(); console.info("Report ready", report.id); } ``` ## Cron syntax ```text ┌───────────── second (optional, 0-59) │ ┌─────────── minute (0-59) │ │ ┌───────── hour (0-23) │ │ │ ┌─────── day of month (1-31) │ │ │ │ ┌───── month (1-12) │ │ │ │ │ ┌─── day of week (0-6, Sunday is 0) │ │ │ │ │ │ * * * * * * ``` Each field accepts `*`, a number or a step such as `*/15`. | Expression | Runs | | ---------------- | ----------------------------------------- | | `* * * * *` | Every minute. | | `*/5 * * * *` | Every 5 minutes. | | `*/30 * * * * *` | Every 30 seconds. | | `0 */3 * * *` | Every 3 hours, on the hour. | | `0 9 * * 1` | Every Monday at 09:00. | | `30 2 1 * *` | At 02:30 on the first day of every month. | > **Note** > > Ranges (`1-5`) and lists (`1,3,5`) aren't accepted. Since trigger names are handler names, export one small handler per schedule and let them call the same code, for example `mondayDigest` with `0 9 * * 1` and `wednesdayDigest` with `0 9 * * 3`. ## Good practices - **Make runs idempotent.** A slow run can overlap with the next one, and a failed run leaves partial work behind. Use flags or timestamps in your data to skip work that is already done. - **Process in batches.** Fetch and update documents page by page, and stay well under the function's `timeout`. - **Record progress.** Store a "last processed" marker in a bucket so the next run continues where the last one stopped. - **Mind multiple replicas.** With several API replicas, turn on `--replication` so that each scheduled run is claimed by exactly one replica. See the [Scheduled cleanup](https://docs.spicaengine.com/recipes/scheduled-cleanup) recipe for a complete example. --- # System, firehose, gRPC and RabbitMQ triggers > Run functions when the API starts, exchange low-latency messages over WebSocket, serve gRPC methods and consume RabbitMQ queues and streams. ## System The `system` trigger runs when the API reaches a lifecycle event. `READY` fires once the API has started, which is the right moment to seed data or warm caches. ```yaml triggers: onReady: type: system active: true options: name: READY ``` ```javascript export async function onReady() { console.info("Spica is ready"); } ``` With several API replicas, `READY` fires on every replica. Make the handler idempotent. ## Firehose The firehose is a WebSocket endpoint for low-latency, bidirectional messaging, such as presence, typing indicators and games. Clients connect to: ```text wss://api.example.com/api/firehose ``` Messages in both directions are JSON objects with a `name` and `data`: ```json {"name": "chat:message", "data": {"room": "general", "text": "Hi!"}} ``` ```yaml triggers: onConnection: type: firehose active: true options: event: "**" onChatMessage: type: firehose active: true options: event: chat:message ``` | `event` | Fires on | | --------------------- | -------------------------------------------- | | `*` | Every message. | | `**` | Connection events: `connection` and `close`. | | `connection`, `close` | A client connected or disconnected. | | Any other name | Messages with that `name`. | The handler receives the client and the pool of all clients, plus the message: ```javascript export function onConnection({socket, pool}, message) { if (message.name == "connection") { pool.send("presence", {online: pool.size}); } } export function onChatMessage({socket, pool}, message) { if (!message.data?.text) { return socket.send("error", {message: "text is required"}); } pool.send("chat:message", {from: socket.id, text: message.data.text}); } ``` | Object | Members | | --------- | ---------------------------------------------------- | | `socket` | `id`, `remoteAddress`, `send(name, data)`, `close()` | | `pool` | `size`, `send(name, data)` to every connected client | | `message` | `name`, `data` | ```javascript // Browser const socket = new WebSocket("wss://api.example.com/api/firehose"); socket.onmessage = event => console.log(JSON.parse(event.data)); socket.onopen = () => socket.send(JSON.stringify({name: "chat:message", data: {text: "Hi!"}})); ``` > **Warning** > > The firehose doesn't authenticate connections. Authenticate inside your handlers, for example by sending a token in the first message and verifying it with the [devkit](https://docs.spicaengine.com/devkit/auth). ## gRPC The `grpc` trigger exposes a handler as a unary gRPC method. The gRPC server listens on `--grpc-function-port` (default `50051`). ```yaml triggers: GetQuote: type: grpc active: true options: requestParams: - {name: symbol, type: string} responseParams: - {name: symbol, type: string} - {name: price, type: double} ``` Parameter types: `string`, `int32`, `int64`, `float`, `double`, `bool`, `bytes`. Spica generates the service definition from the function and handler names. For a function named `quotes`, the trigger above becomes: ```text syntax = "proto3"; package quotes; service quotes { rpc GetQuote (GetQuoteRequest) returns (GetQuoteResponse); } message GetQuoteRequest { string symbol = 1; } message GetQuoteResponse { string symbol = 1; double price = 2; } ``` The handler receives the request message as an object and returns the response object: ```javascript export async function GetQuote(request) { const price = await lookupPrice(request.symbol); return {symbol: request.symbol, price}; } ``` A thrown error is returned to the client with status code `13` (`INTERNAL`). The maximum message size is `--function-grpc-max-message-size-bytes` (25 MiB by default). > **Note** > > Expose port `50051` from the API container to reach gRPC functions. The Helm chart opens it on the API pod. ## RabbitMQ The `rabbitmq` trigger consumes messages from RabbitMQ, either from a queue over AMQP 0.9.1 (`mode: queue`, the default) or from a stream over the RabbitMQ Stream protocol (`mode: stream`). ### Queue mode ```yaml triggers: processOrder: type: rabbitmq active: true options: mode: queue url: ${SECRET.RABBITMQ_URL} exchange: name: orders type: topic queue: name: spica-orders durable: true bindings: [] prefetch: 10 noAck: false ``` | Option | Description | | ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | | `url` | **Required.** `amqp://` or `amqps://` URL. Connection parameters such as `heartbeat` can be added as query parameters. | | `socketOptions` | TLS and socket options: `ca`, `cert`, `key`, `passphrase`, `servername`, `rejectUnauthorized`, `timeout`, `clientProperties`. | | `exchange` | Exchange to declare and bind the queue to: `name`, `type` (`direct`, `fanout`, `topic`, `headers` or a plugin type) and options. | | `queue` | Queue to declare and consume: `name` (empty lets the broker choose), `durable`, `exclusive` and other options. | | `bindings` | Extra bindings of the queue to existing exchanges, with routing key patterns. | | `exchangeBindings` | Bindings between exchanges. | | `prefetch`, `prefetchGlobal` | How many unacknowledged messages the broker delivers at once. | | `consume` | Consumer options such as `consumerTag`, `exclusive` and `priority`. | | `noAck` | Default `true`: messages count as acknowledged on delivery. Set `false` to acknowledge from your code. | The handler receives the message and a channel: ```javascript export async function processOrder(message, channel) { const order = JSON.parse(message.content.toString()); try { await fulfil(order); await channel.ack(message); } catch (error) { console.error("Order failed", order.id, error); await channel.nack(message, false, true); } } ``` | Channel method | Description | | ----------------------------------- | -------------------------------------- | | `ack(message, allUpTo?)` | Acknowledge a message. | | `nack(message, allUpTo?, requeue?)` | Reject a message, requeued by default. | | `reject(message, requeue?)` | Reject a single message. | | `ackAll()`, `nackAll(requeue?)` | Settle every outstanding message. | `message` has `content` (a `Buffer`), `fields` and `properties`. ### Stream mode ```yaml options: mode: stream connection: hostname: rabbitmq.internal port: 5552 username: ${SECRET.RABBITMQ_USER} password: ${SECRET.RABBITMQ_PASSWORD} stream: name: orders consumer: offset: type: first consumerRef: spica-orders ``` | Option | Description | | ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | | `connection` | `hostname`, `port` (default `5552`), `vhost`, `username`, `password` and protocol settings. | | `stream` | `name` of the stream to declare and consume, and optional arguments such as retention. | | `consumer.offset` | Where to start: `type` is `first`, `last`, `next`, `offset` (with a numeric `value`) or `timestamp` (with an ISO date or epoch milliseconds). | | `consumer.consumerRef` | Name under which the broker stores this consumer's offset. Required for `storeOffset` and for resuming after a restart. | | `consumer.singleActive` | Only one consumer with the same `consumerRef` receives messages at a time. | The broker must have the `rabbitmq_stream` plugin enabled. Behind Docker, NAT or a load balancer, set `stream.advertised_host` and `stream.advertised_port` on the broker so clients can reach it. The handler receives the message, including its `offset`, and a consumer that can store offsets: ```javascript export async function onOrderEvent(message, consumer) { console.info("offset", message.offset, message.content.toString()); await consumer.storeOffset(); } ``` Keep connection details in [secrets](https://docs.spicaengine.com/functions/environment) and reference them with `${SECRET.NAME}` placeholders as shown above. --- # Dependencies & builds > Install npm packages into functions, write functions in TypeScript, share code between functions and choose how sources are built. ## npm dependencies Each function has its own `package.json` and `node_modules`. Install packages from the panel's **Dependencies** box, with the CLI, or over the API: ```bash curl -X POST https://api.example.com/api/function//dependencies \ -H "Authorization: APIKEY " \ -H "Content-Type: application/json" \ -d '{"name": ["@spica-devkit/bucket@0.22.1", "dayjs@^1.11.0"]}' ``` ```bash curl https://api.example.com/api/function//dependencies \ -H "Authorization: APIKEY " ``` ```json [{"name": "@spica-devkit/bucket", "version": "^0.22.1"}, {"name": "dayjs", "version": "^1.11.0"}] ``` Remove a package with `DELETE /function//dependencies/`. Scoped names work as they are, for example `DELETE /function//dependencies/@spica-devkit/bucket`. In a [CLI project](https://docs.spicaengine.com/cli/resources-as-code), dependencies live in `function//package.json`. `spica apply` and `spica dev` install what changed. ```json title="function/hello/package.json" { "name": "hello", "version": "0.0.1", "dependencies": { "@spica-devkit/bucket": "^0.22.1", "dayjs": "^1.11.0" } } ``` > **Tip** > > Pin the devkit to the version of your Spica instance, and pin every other dependency to a range you have tested. A fresh install picks the newest version inside the range. ## TypeScript Set `language: typescript` and write `index.ts`. Spica compiles it when you save, and rejects code with type or syntax errors with `422` and a list of diagnostics with line and column. JavaScript is saved without checks, so a syntax error only shows up when the function runs: ```typescript title="function/greet/index.ts" import * as Bucket from "@spica-devkit/bucket"; interface Post { _id: string; title: string; status: "draft" | "published"; } export default async function (req: any): Promise { Bucket.initialize({apikey: process.env.SPICA_API_KEY}); return Bucket.data.getAll(process.env.POSTS_BUCKET_ID, { queryParams: {filter: 'document.status == "published"', limit: 10} }); } ``` Generate types for your buckets with [`spica bucket orm`](https://docs.spicaengine.com/cli/orm) and import them into your functions. ## Sharing code between functions Any function can be imported by another one as `@spica-fn/`: ```json {"name": ["@spica-fn/text-utils"]} ``` ```javascript import * as TextUtils from "@spica-fn/text-utils"; ``` The dependency is recorded as a local package (`file:../text-utils`). When you change the imported function, Spica rebuilds the functions that depend on it. Keep shared helpers in functions without triggers so they don't run on their own. ## Builders The API turns function sources into runnable code with one of two builders, set by `--function-builder`: | Builder | What it does | Use it when | | ------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------ | | `legacy` (default) | Compiles the entry file and loads dependencies from `node_modules` at runtime. | You want the long-standing behaviour. | | `rollup` | Bundles the entry file with its local imports and dependencies into one file. | You want faster cold starts and self-contained builds. | Bundling large dependency graphs needs memory. Raise `--function-builder-max-memory` (in MB) when builds fail with out-of-memory errors, and keep it below your container's memory limit. ## Where sources are stored Function sources and their installed packages are kept on disk under the API's persistent path, and can also be stored in a shared location so that every API replica sees the same code: | `--function-asset-storage-strategy` | Location | | ----------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | | `default` | `--function-asset-path`. Point every replica at the same shared volume. | | `awss3` | An S3 bucket: `--function-asset-awss3-bucket-name`, credentials from `--function-asset-awss3-credentials-path` or the AWS default chain. | | `gcs` | A Google Cloud Storage bucket: `--function-asset-gcs-bucket-name` and `--function-asset-gcs-service-account-path`. | See the [configuration reference](https://docs.spicaengine.com/self-hosting/configuration#functions). --- # Environment variables & secrets > Give functions configuration and credentials through environment variables and encrypted secrets, and reference them in trigger options. Functions read configuration from `process.env`. Spica manages two kinds of values: | | Environment variables | Secrets | | ------------------------- | --------------------------------------- | ---------------------------------------- | | Use for | Configuration: ids, URLs, feature flags | Credentials: API keys, passwords, tokens | | Stored | As plain text | Encrypted with the secret module key | | Readable over the API | Yes | Never. Only a salted hash is returned. | | Visible in the panel | Yes | No | | Exported by `spica fetch` | Yes, including values | Only the key | Both are created once and then **attached** to the functions that need them. ## Create values **Panel** Open **Access Management → Secrets and Variables**, or the **Environment** box of a function, and add a key and a value. **REST API** ```bash curl -X POST https://api.example.com/api/env-var \ -H "Authorization: APIKEY " -H "Content-Type: application/json" \ -d '{"key": "POSTS_BUCKET_ID", "value": "6b0b1968a5611972c29c25f7"}' curl -X POST https://api.example.com/api/secret \ -H "Authorization: APIKEY " -H "Content-Type: application/json" \ -d '{"key": "STRIPE_KEY", "value": "sk_live_..."}' ``` A secret is returned without its value: ```json {"_id": "6b0b1a93a5611972c29c2623", "key": "STRIPE_KEY", "salt": "16745bff...", "value_hash": "f7a2bd56...", "updated_at": "2026-11-28T18:16:51.516Z"} ``` **CLI** Declare the key in your project and set the value for the current context. Values are kept out of git: ```bash mkdir -p secret/STRIPE_KEY echo "key: STRIPE_KEY" > secret/STRIPE_KEY/schema.yaml spica secret STRIPE_KEY ``` See [Values per environment](https://docs.spicaengine.com/cli/values). ## Attach values to a function ```bash curl -X PUT https://api.example.com/api/function//env-var/ \ -H "Authorization: APIKEY " curl -X PUT https://api.example.com/api/function//secret/ \ -H "Authorization: APIKEY " ``` Detach them with `DELETE` on the same URLs. In a function's `schema.yaml` the attached ids are listed under `env_vars` and `secrets`. ## Read values in code ```javascript export default async function () { const bucketId = process.env.POSTS_BUCKET_ID; const stripe = new Stripe(process.env.STRIPE_KEY); } ``` Workers are restarted with the new values when you change or attach them. ## Placeholders in trigger options Trigger options and the numeric settings `timeout`, `warmWorkers` and `concurrencyPerWorker` can reference attached values: ```yaml timeout: ${ENV.ORDER_TIMEOUT} triggers: processOrder: type: rabbitmq active: true options: url: ${SECRET.RABBITMQ_URL} queue: name: ${ENV.ORDER_QUEUE} ``` - `${ENV.KEY}` resolves an attached environment variable, `${SECRET.KEY}` an attached secret. - Only values attached to the function are resolved. - Numeric settings must resolve to valid numbers, otherwise the default is used and a warning is logged. ## Permissions | Action | Allows | | ------------------------------------------------------------------------------------- | ---------------------------------------------- | | `env-var:index`, `env-var:show`, `env-var:create`, `env-var:update`, `env-var:delete` | Managing environment variables. | | `secret:index`, `secret:show`, `secret:create`, `secret:update`, `secret:delete` | Managing secrets. | | `function:env-var:inject`, `function:env-var:eject` | Attaching and detaching environment variables. | | `function:secret:inject`, `function:secret:eject` | Attaching and detaching secrets. | > **Warning** > > Anyone who can change a function's code can read the secrets attached to it. Grant function update permissions as carefully as secret permissions. --- # Logs > Write logs from functions with the console, browse and filter them in the panel or over the API, and send them to stdout for your log platform. Everything a function writes with `console` is captured, tagged with the function and the event, and stored by Spica. ```javascript export default function (req) { console.debug("query", JSON.stringify(req.query)); console.info(`Greeting ${req.query.name}`); console.warn("Long name received", req.query.name.length); console.error("Something failed"); console.log("Plain log line"); } ``` ## Levels | Method | Level | Value | | --------------- | ------- | ----- | | `console.debug` | Debug | `0` | | `console.log` | Log | `1` | | `console.info` | Info | `2` | | `console.warn` | Warning | `3` | | `console.error` | Error | `4` | Levels are recorded when `--function-logger` is on, which is the default. ## In the panel Open **Functions → Logs** to see logs of every function on a timeline, filter them by level, function, time range and text, and expand an entry to see its details. ![The function logs page with a timeline chart and a table of log entries with severity, timestamp, function, handler and content](https://docs.spicaengine.com/screenshots/panel/function-logs.webp) ## Over the API `GET /function-logs` | Query parameter | Description | | --------------- | ---------------------------------------------------------------------- | | `functions` | Function ids. Repeat for several. | | `levels` | Level values, for example `levels=3&levels=4` for warnings and errors. | | `content` | Text to search for. | | `begin`, `end` | Time range. Defaults to the current day. | | `channel` | `stdout` or `stderr`. | | `limit`, `skip` | Pagination. | ```bash curl -G https://api.example.com/api/function-logs \ -H "Authorization: APIKEY " \ --data-urlencode "functions=" \ --data-urlencode "levels=4" \ --data-urlencode "limit=20" ``` ```json [ { "_id": "6b0b1a67a5611972c29c261e", "function": "hello", "event_id": "2u2l9r31mx0qedf6", "channel": "stdout", "level": 1, "content": "New post created 6b0b1a67a5611972c29c261c", "created_at": "2026-11-28T18:16:07.799Z" } ] ``` `DELETE /function-logs/` removes the logs of a function. ## Retention Logs expire after `--common-log-lifespan` seconds, one month by default. The same setting applies to activity and status records. ## Sending logs to your platform Choose where worker output goes with `--function-worker-log-output`: | Value | Effect | | -------------------- | ------------------------------------------------------------------------------------------------ | | `database` (default) | Stored by Spica and visible in the panel and API. | | `stdout` | Written to the API container's standard output, for Loki, CloudWatch, Datadog and similar tools. | | `database,stdout` | Both. | Add `--function-invocation-logs=true` to also log every invocation to stdout. ## Good logging - Log identifiers (`documentKey`, user ids, order ids) so you can correlate events. - Use `warn` and `error` for things someone should look at, and filter on them. - Don't log secrets, tokens or personal data. - Keep `debug` logs cheap, or remove them once a function is stable. --- # Runtime & scaling > How function workers run your code, and how timeouts, warm workers and concurrency settings affect latency and throughput. ## Workers Function code runs in **workers**: Node.js 22 processes started by the API. Each worker belongs to one function and handles that function's events. When an event arrives, the API sends it to a free worker or starts a new one. The first event of a fresh worker pays a **cold start**: Node.js starts and your module and its dependencies are loaded. Code at the top level of your module runs once per worker, so it's the right place for expensive setup that can be reused, such as SDK clients. ```javascript import * as Bucket from "@spica-devkit/bucket"; Bucket.initialize({apikey: process.env.SPICA_API_KEY}); const cache = new Map(); export default async function (req) { // Runs per event. The client and the cache are reused across events. } ``` ## Settings per function | Setting | Default | Effect | | ---------------------- | ------- | -------------------------------------------------------------------------------------------------------- | | `timeout` | | Seconds an event may run. Capped by `--function-timeout`. | | `warmWorkers` | `0` | Workers kept started and loaded, so events skip the cold start. Capped by `--function-warm-workers-max`. | | `concurrencyPerWorker` | `1` | Events one worker runs at the same time. Capped by `--function-worker-event-concurrency`. | All three accept [`${ENV.KEY}` placeholders](https://docs.spicaengine.com/functions/environment#placeholders-in-trigger-options), so you can tune them per environment. ### When to raise `concurrencyPerWorker` Raise it for I/O-bound handlers that mostly wait on the network or the database, such as API proxies. Keep it at `1` for CPU-heavy handlers and for code that keeps per-event state in module-level variables. ### When to use warm workers Use them for user-facing HTTP functions with strict latency targets. Each warm worker is a running Node.js process, so they cost memory even when idle. ## Instance-wide settings | Option | Default | Effect | | ------------------------------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `--function-timeout` | `60` | Upper bound for every function's `timeout`, in seconds. | | `--function-worker-concurrency` | `2` | Workers that can run in parallel for the same function. | | `--function-worker-event-concurrency` | `100` | Upper bound for `concurrencyPerWorker`. | | `--function-warm-workers-max` | `10` | Upper bound for `warmWorkers`. `0` disables warm workers. | | `--function-worker-cutover-grace-ms` | `30000` | When you deploy new code under traffic, old workers keep serving until the new ones are ready. After this many milliseconds they are retired anyway, so a broken release surfaces. | | `--function-limit` | | Maximum number of functions. | | `--function-debug` | `false` | Starts workers in debugging mode. | | `--payload-size-limit` | `15` | Maximum request body size in MiB, for functions and the rest of the API. | ## Deploying new code When you save a function, Spica builds it and replaces the workers. Events that already started finish on the old code. New events go to the new workers once they're ready. ## Timeouts When an event exceeds its timeout, Spica aborts it and logs a message such as `10 seconds timeout value has been reached for function 'onPost'`. An HTTP request whose handler times out gets no response from the function, so the client waits until its own timeout or the proxy's, which usually answers `504 Gateway Time-out`. Design for timeouts: - Return HTTP responses quickly and continue heavy work elsewhere, for example in a bucket trigger or a queue consumer. - Process scheduled work in batches that fit in the timeout. - Set timeouts close to the real duration of the handler, so stuck events are released early. ## Calling the API from functions Functions reach the API at `--function-api-url`, which defaults to `http://127.0.0.1:`, a loopback connection that skips your ingress. The devkit uses it automatically. Set it explicitly when workers can't reach the API on localhost. ## Debugging Use logs first: add `console.debug` lines and filter on them in **Functions → Logs**. For local development, run Spica with `spica project start` and iterate with [`spica dev`](https://docs.spicaengine.com/cli/resources-as-code#develop-with-live-sync), which applies your file changes as you save. --- # Function best practices > Practical guidelines for writing functions that are fast, secure, observable and easy to change. ## Structure - **One function per responsibility.** Group the handlers of one feature (for example "orders") in one function, and put unrelated features in separate functions. Each function has its own workers, dependencies and timeout. - **Share code through imports.** Put helpers in a trigger-less function and import it with `@spica-fn/` instead of copying code. See [Sharing code](https://docs.spicaengine.com/functions/dependencies#sharing-code-between-functions). - **Use TypeScript for larger functions**, and generate bucket types with [`spica bucket orm`](https://docs.spicaengine.com/cli/orm). - **Keep functions in git** with the [CLI](https://docs.spicaengine.com/cli/resources-as-code), and review changes with `spica plan` before applying them. ## Performance - **Initialize clients at module level.** `Bucket.initialize`, SDK clients and connection pools should be created once per worker, not per event. - **Return HTTP responses fast.** Do slow work after responding, in a bucket trigger, a queue consumer or a schedule. - **Batch your API calls.** Use `insertMany`, `removeMany` and the [batch endpoint](https://docs.spicaengine.com/platform/batch) instead of loops of single requests. - **Ask only for what you need.** Send `limit`, avoid `paginate=true` unless you need totals, and resolve only the relations you use. - **Tune per function.** Raise `concurrencyPerWorker` for I/O-bound handlers and add `warmWorkers` for latency-sensitive endpoints. See [Runtime & scaling](https://docs.spicaengine.com/functions/runtime). ## Security - **Keep credentials in secrets**, never in code or environment variables. - **Give functions narrow API keys.** Create an API key per function or feature with only the policies it needs, store it as a secret, and use it with the devkit. - **Authenticate HTTP routes** with `authenticate` and `authorize`, and validate request bodies yourself. - **Remember that API keys bypass rules.** When a function acts on behalf of a user, check what that user may do, or forward the user's token to the API instead of using a key. - **Rate-limit public endpoints** with the `rateLimit` option. ## Reliability - **Make handlers idempotent.** Data triggers, schedules and queue consumers can see the same work more than once. Check before you write. - **Guard against trigger loops.** A bucket trigger that writes to its own bucket fires again. - **Set realistic timeouts** and design long jobs as batches that each fit in one event. - **Acknowledge queue messages explicitly** (`noAck: false`) when losing a message is not acceptable. ## Observability - **Log with levels** and include ids so that you can filter and correlate. - **Watch errors.** Filter logs by level `4` in the panel, or send worker output to `stdout` with `--function-worker-log-output` and alert on it in your log platform. - **Name triggers after what they do** (`onOrderPaid`, `nightlyReport`), because handler names appear in logs. ## Local development loop 1. Start a local instance with `spica project start dev`. 2. Fetch your project files with `spica fetch`. 3. Run `spica dev` and edit code. Changes are applied as you save. 4. Use `spica plan` to review the changes, commit, and let CI run `spica apply` against staging and production. --- # Authentication & access > How Spica authenticates identities, users and API keys, and how policies and rules decide what each of them may do. Spica's authentication and authorization module is called **Passport**. It answers two questions for every request: 1. **Who is calling?** An identity, a user or an API key, proven by the `Authorization` header. 2. **What may they do?** Decided by the [policies](https://docs.spicaengine.com/auth/policies) attached to the caller, and for users also by [bucket rules](https://docs.spicaengine.com/buckets/rules). ## Three kinds of callers - [Identities](https://docs.spicaengine.com/auth/identities): Your team: developers, editors and operators who use the panel and the management APIs. - [Users](https://docs.spicaengine.com/auth/users): Your product's end users, with sign-up, verification, password reset and passwordless login. - [API keys](https://docs.spicaengine.com/auth/api-keys): Servers, functions, scripts, CI pipelines and the CLI. | | Identity | User | API key | | ------------------------- | -------------------------------- | ----------------------------------------------- | -------------------------------- | | Credential | Identifier and password, or SAML | Username and password, OTP, magic link or OAuth | A static key | | Header | `Authorization: IDENTITY ` | `Authorization: USER ` | `Authorization: APIKEY ` | | Expires | Yes, refreshable | Yes, refreshable | No, until deactivated or deleted | | Bucket rules applied | No | Yes | No | | Two-factor authentication | TOTP | TOTP | No | ## The request lifecycle ```text Authorization header → authenticate: verify the token or key 401 when it fails → authorize: policies allow the action on the resource 403 when they don't → rules: for USER requests on bucket data, filter or reject documents → handler ``` Policies are evaluated on every request, so changes to policies take effect immediately, even for tokens that were issued earlier. ## In this section | Page | Covers | | ------------------------------------------------------------------------- | ----------------------------------------------------------------------- | | [Identities](https://docs.spicaengine.com/auth/identities) | Creating team accounts, the default identity, logging in. | | [Users](https://docs.spicaengine.com/auth/users) | Sign-up, login, verification, password reset, passwordless login, bans. | | [Tokens & sessions](https://docs.spicaengine.com/auth/tokens) | JWT lifetimes, refresh tokens, verifying and revoking tokens. | | [API keys](https://docs.spicaengine.com/auth/api-keys) | Creating keys, attaching policies, rotating keys. | | [Policies](https://docs.spicaengine.com/auth/policies) | Statements, actions, resources and the built-in policies. | | [Strategies](https://docs.spicaengine.com/auth/strategies) | SAML for identities, OAuth providers for users. | | [Two-factor authentication](https://docs.spicaengine.com/auth/two-factor) | TOTP setup and login challenges. | | [Password & login security](https://docs.spicaengine.com/auth/security) | Password policies, history, lockout and rate limits. | --- # Identities > Create accounts for the people who build and operate your backend, give them policies, and log them in to the panel and the API. Identities are accounts for your team: developers, content editors, support staff and operators. They log in to the panel, and their tokens can call every management API their policies allow. ![The identities list in the panel's Access Management section](https://docs.spicaengine.com/screenshots/panel/identity.webp) ## The default identity Every instance starts with one identity that has full access: | Setting | API option | Default | | ---------- | ---------------------------------------- | -------------------------- | | Identifier | `--passport-default-identity-identifier` | `spica` | | Password | `--passport-default-identity-password` | `spica` | | Policies | `--passport-default-identity-policies` | All `*FullAccess` policies | > **Danger** > > Change the default password before you expose an instance. In production, set `--passport-default-identity-password` (or `application.defaultPassword` in the Helm chart) to a strong value, or create personal identities and delete the default one. ## Log in `POST /passport/identify` ```bash curl -X POST https://api.example.com/api/passport/identify \ -H "Content-Type: application/json" \ -d '{"identifier": "spica", "password": "spica", "expires": 3600}' ``` ```json {"scheme": "IDENTITY", "token": "eyJhbGciOiJIUzI1NiIs...", "issuer": "passport/identity"} ``` | Field | Description | | ------------------------ | --------------------------------------------------------------------------------------------------------------------- | | `identifier`, `password` | Credentials. | | `expires` | Optional token lifetime in seconds, up to the server's limit. See [Tokens](https://docs.spicaengine.com/auth/tokens). | Use the token as `Authorization: IDENTITY `. The response also sets a refresh token cookie, see [Tokens & sessions](https://docs.spicaengine.com/auth/tokens#refresh-tokens). Wrong credentials return `401` with `Identifier or password was incorrect.` When the identity has [two-factor authentication](https://docs.spicaengine.com/auth/two-factor), the response is a challenge instead of a token. ## Manage identities | Endpoint | Action | | ------------------------------------------------ | --------------------------------- | | `GET /passport/identity` | `passport:identity:index` | | `GET /passport/identity/:id` | `passport:identity:show` | | `POST /passport/identity` | `passport:identity:create` | | `PUT /passport/identity/:id` | `passport:identity:update` | | `DELETE /passport/identity/:id` | `passport:identity:delete` | | `PUT /passport/identity/:id/policy/:policyId` | `passport:identity:policy:add` | | `DELETE /passport/identity/:id/policy/:policyId` | `passport:identity:policy:remove` | Create an identity, then attach policies to it: ```bash curl -X POST https://api.example.com/api/passport/identity \ -H "Authorization: IDENTITY " -H "Content-Type: application/json" \ -d '{"identifier": "editor", "password": "a-long-random-password"}' curl -X PUT https://api.example.com/api/passport/identity//policy/BucketFullAccess \ -H "Authorization: IDENTITY " ``` ```json {"identifier": "editor", "policies": [], "_id": "6b0b1b36a5611972c29c2643"} ``` New identities have no policies. They can log in, but every API call returns `403` until you attach some. ## Typical roles | Role | Policies | | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Developer | The `*FullAccess` policies of the modules they work on. | | Content editor | A [custom policy](https://docs.spicaengine.com/auth/policies#example-content-editor) with the data actions of the content buckets, plus `StorageFullAccess` for images. | | Support | `UserReadOnlyAccess`, `ActivityReadOnlyAccess` and read-only data access. | | Auditor | The `*ReadOnlyAccess` policies. | ## Profile and permissions of the current identity | Endpoint | Returns | | ----------------------------------- | ----------------------------------------------------------------------------- | | `GET /passport/identity/verify` | The decoded token. Send the raw token in `Authorization`, without the scheme. | | `GET /passport/identity/statements` | Every policy statement that applies to the caller. | ## Limits and settings | API option | Effect | | ------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------- | | `--passport-identity-limit` | Maximum number of identities. | | `--passport-identity-token-expires-in` | Default token lifetime, 2 days. | | `--passport-identity-token-expiration-seconds-limit` | Longest lifetime a client can request with `expires`. | | `--passport-identity-password-history-limit` | Previous passwords that can't be reused. | | `--passport-identity-failed-login-attempt-limit`, `--passport-identity-block-duration-after-failed-login-attempts` | Lockout after failed logins. | Password rules such as minimum length are set in the `identity` [configuration](https://docs.spicaengine.com/auth/security#password-policy). --- # Users > Manage your product's end users with Spica, from sign-up and login to email and phone verification, password reset, passwordless login and bans. Users are the end users of your product. They log in with a username and password, a one-time code or magic link, or an OAuth provider, and they reach your data through policies and [bucket rules](https://docs.spicaengine.com/buckets/rules). ![The users list in the panel's Access Management section](https://docs.spicaengine.com/screenshots/panel/user.webp) ## Create users `POST /passport/user` requires an identity or an API key with the `passport:user:create` action. Users can't call it anonymously, so sign-up goes through your backend, typically an [HTTP function](https://docs.spicaengine.com/recipes/user-signup-verification): ```bash curl -X POST https://api.example.com/api/passport/user \ -H "Authorization: APIKEY " -H "Content-Type: application/json" \ -d '{"username": "reader1", "password": "readerPass1"}' ``` ```json {"username": "reader1", "policies": [], "_id": "6b0b1adea5611972c29c2631"} ``` | Field | Description | | ---------------------- | ---------------------------------------------------------------------------------------------------------------- | | `username` | **Required.** At least 3 characters, unique. Often an email address. | | `password` | **Required.** Checked against the [password policy](https://docs.spicaengine.com/auth/security#password-policy). | | `bannedUntil` | Optional date until which the user can't log in. | | `deactivateJwtsBefore` | Optional Unix timestamp in seconds. Tokens issued before it are rejected. | Then attach the policies users need, for example a policy that allows reading and writing your app's buckets: ```bash curl -X PUT https://api.example.com/api/passport/user//policy/ \ -H "Authorization: APIKEY " ``` The number of users can be limited with `--passport-user-limit`. Account creation is rate limited by the `createUser` [rate limit](https://docs.spicaengine.com/auth/security#rate-limits). ## Log in `POST /passport/login` ```bash curl -X POST https://api.example.com/api/passport/login \ -H "Content-Type: application/json" \ -d '{"username": "reader1", "password": "readerPass1"}' ``` ```json {"scheme": "USER", "token": "eyJhbGciOiJIUzI1NiIs..."} ``` Use the token as `Authorization: USER `. Its payload contains the user's `_id`, `username` and `policies`, which [rules](https://docs.spicaengine.com/buckets/rules) can read through `auth`. The response also sets a refresh token cookie, see [Tokens & sessions](https://docs.spicaengine.com/auth/tokens). ## What users can do on their own account Without any extra policy, a logged-in user can: | Endpoint | Purpose | | ------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | | `GET /passport/user/:id` | Read their own record. | | `PUT /passport/user/:id/self` | Change their password: `{"password": "..."}`. | | `POST /passport/user/:id/start-factor-verification`, `.../complete-factor-verification`, `DELETE .../factors` | Manage [two-factor authentication](https://docs.spicaengine.com/auth/two-factor). | Everything else needs a policy. Attaching an email address or phone number to an account requires `passport:user:update`, so run it from a function with an API key after you have verified the user's token. ## Email and phone verification Users can prove ownership of an email address or a phone number, which then enables password reset and passwordless login through that channel. Emails are sent through the [mailer](https://docs.spicaengine.com/platform/mailer-and-sms) and SMS through Twilio. Enable the provider and strategy in the `user` [configuration](https://docs.spicaengine.com/platform/config): ```json { "providerVerificationConfig": [ {"provider": "email", "strategy": "Otp"}, {"provider": "phone", "strategy": "Otp"} ] } ``` | Strategy | What the user receives | | ----------- | ------------------------------------------------------------------- | | `Otp` | A 6-digit code, by default `Your verification code is: 123456`. | | `MagicLink` | A link to `/passport/user/verify-magic-link?token=...`. | Start and complete the verification: ```bash curl -X POST https://api.example.com/api/passport/user//start-provider-verification \ -H "Authorization: APIKEY " -H "Content-Type: application/json" \ -d '{"value": "ada@example.com", "provider": "email", "strategy": "Otp", "purpose": "verification"}' curl -X POST https://api.example.com/api/passport/user//verify-provider \ -H "Authorization: APIKEY " -H "Content-Type: application/json" \ -d '{"code": "123456", "provider": "email", "strategy": "Otp", "purpose": "verification"}' ``` The number of attempts is limited by `verificationProcessMaxAttempt`, and codes expire after `--passport-user-verification-code-expires-in` seconds (5 minutes by default). ## Password reset Enable a provider in the `user` configuration: ```json {"resetPasswordProvider": [{"provider": "email", "strategy": "Otp"}]} ``` Then let the user request a code and set a new password. Neither call needs a token: ```bash curl -X POST https://api.example.com/api/passport/user/forgot-password/start \ -H "Content-Type: application/json" \ -d '{"username": "reader1", "provider": "email"}' curl -X POST https://api.example.com/api/passport/user/forgot-password/verify \ -H "Content-Type: application/json" \ -d '{"username": "reader1", "code": "123456", "newPassword": "aNewPassword1", "provider": "email"}' ``` Without the configuration the API responds with `Provider or Reset password is not configured properly.` ## Passwordless login Enable it in the `user` configuration: ```json {"passwordlessLogin": {"passwordlessLoginProvider": [{"provider": "email", "strategy": "Otp"}]}} ``` ```bash curl -X POST https://api.example.com/api/passport/user/passwordless-login/start \ -H "Content-Type: application/json" \ -d '{"username": "reader1", "provider": "email"}' curl -X POST https://api.example.com/api/passport/user/passwordless-login/verify \ -H "Content-Type: application/json" \ -d '{"username": "reader1", "code": "123456", "provider": "email"}' ``` The verify call returns a user token like a normal login. Both endpoints are rate limited by the `login` rate limit. ## Ban users and revoke sessions | Goal | How | | ------------------------------------ | ---------------------------------------------------------------------------------- | | Block logins until a date | `PUT /passport/user/:id` with `bannedUntil`. | | Invalidate every token issued so far | `PUT /passport/user/:id` with `deactivateJwtsBefore` set to the current Unix time. | | Remove the account | `DELETE /passport/user/:id`. | The [auth devkit](https://docs.spicaengine.com/devkit/auth) offers `ban` and `deactivateUserTokens` helpers. ## Manage users | Endpoint | Action | | -------------------------------------------- | ----------------------------- | | `GET /passport/user` | `passport:user:index` | | `GET /passport/user/:id` | `passport:user:show` | | `POST /passport/user` | `passport:user:create` | | `PUT /passport/user/:id` | `passport:user:update` | | `DELETE /passport/user/:id` | `passport:user:delete` | | `PUT /passport/user/:id/policy/:policyId` | `passport:user:policy:add` | | `DELETE /passport/user/:id/policy/:policyId` | `passport:user:policy:remove` | ## Identities or users? Use **users** for anyone who signs up to your product. Use **identities** only for people who operate the backend. Users never see the panel, and identities never pass through bucket rules. --- # Tokens & sessions > How Spica issues and verifies JWTs for identities and users, how refresh tokens extend sessions, and how to revoke them. ## Access tokens A successful login returns a JWT signed with the API's `passport-secret`: ```json {"scheme": "USER", "token": "eyJhbGciOiJIUzI1NiIs..."} ``` Send it as `Authorization: `. The payload of a user token looks like this: ```json { "_id": "6b0b1adea5611972c29c2631", "username": "reader1", "policies": ["6b0b1aeba5611972c29c2635"], "lastLogin": "2026-11-28T18:18:06.100Z", "iat": 1795889886, "exp": 1796062686, "aud": "spica.io", "iss": "https://api.example.com/api" } ``` ### Lifetime | Option | Identities | Users | | ---------------------------- | ---------------------------------------------------- | ------------------------------------------------ | | Default lifetime | `--passport-identity-token-expires-in` (2 days) | `--passport-user-token-expires-in` (2 days) | | Maximum a client may request | `--passport-identity-token-expiration-seconds-limit` | `--passport-user-token-expiration-seconds-limit` | Clients can ask for a shorter or longer token with `expires` (seconds) in the login body, up to the maximum: ```json {"identifier": "spica", "password": "spica", "expires": 900} ``` ## Refresh tokens Login responses also set an HTTP-only cookie with a refresh token: ```http Set-Cookie: refreshToken=eyJ...; Max-Age=259200; Path=passport/identity/session/refresh; HttpOnly; Secure; SameSite=None ``` When the access token expires, exchange it for a new one. Send the old access token in `Authorization` and the cookie with the request: | Caller | Endpoint | | -------- | ----------------------------------------- | | Identity | `POST /passport/identity/session/refresh` | | User | `POST /passport/user/session/refresh` | ```javascript const response = await fetch("https://api.example.com/api/passport/user/session/refresh", { method: "POST", credentials: "include", headers: {Authorization: `USER ${expiredToken}`} }); const {token} = await response.json(); ``` Without the cookie the endpoint returns `401` with `Refresh token does not exist.` | Option | Default | | ---------------------------------------------- | ---------------------------------------------------------------------- | | `--passport-identity-refresh-token-expires-in` | 3 days | | `--passport-user-refresh-token-expires-in` | 3 days | | `--refresh-token-hash-secret` | Derived from the master key. Refresh tokens are stored hashed with it. | > **Note** > > The cookie is `Secure` and `SameSite=None`, so browsers only send it over HTTPS (or to `localhost`) and only with `credentials: "include"`. Make sure `--cors-allowed-origins` lists your web app's origin when it runs on a different domain. ## Manage refresh tokens Administrators can list and revoke sessions: | Endpoint | Action | Purpose | | ------------------------------------ | ------------------------------- | ------------------------------------------- | | `GET /passport/refresh-token` | `passport:refresh-token:index` | List sessions. | | `GET /passport/refresh-token/:id` | `passport:refresh-token:show` | Get one. | | `PUT /passport/refresh-token/:id` | `passport:refresh-token:update` | Disable or enable it: `{"disabled": true}`. | | `DELETE /passport/refresh-token/:id` | `passport:refresh-token:delete` | Delete it. | ```json [{"_id": "6b0b1924a5611972c29c25f1", "identity": "6b0b191d988a814684c8fec2", "created_at": "2026-11-28T18:10:44.019Z", "expired_at": "2026-12-01T18:10:44.019Z", "last_used_at": null}] ``` ![The refresh tokens page listing active sessions](https://docs.spicaengine.com/screenshots/panel/refresh-token.webp) ## Verify a token Decode and verify a token on your own backend: | Caller | Endpoint | | -------- | ------------------------------- | | Identity | `GET /passport/identity/verify` | | User | `GET /passport/user/verify` | Send the raw token, without the scheme, in the `Authorization` header. A valid token returns its payload, an invalid one returns `400`. ```bash curl https://api.example.com/api/passport/user/verify -H "Authorization: eyJhbGciOiJIUzI1NiIs..." ``` Inside functions, use `Auth.verifyToken` from [`@spica-devkit/auth`](https://docs.spicaengine.com/devkit/auth) or `Identity.verifyToken` from [`@spica-devkit/identity`](https://docs.spicaengine.com/devkit/identity). ## Revoke access | Goal | How | | -------------------------------------- | ------------------------------------------------------------------------------------------- | | End one session | Disable or delete its refresh token. The current access token stays valid until it expires. | | End every session of a user now | Set `deactivateJwtsBefore` on the user to the current Unix time. | | Lock a user out | Set `bannedUntil` on the user. | | Change what a token can do | Edit or detach policies. Changes apply to existing tokens immediately. | | Invalidate every token of the instance | Rotate `passport-secret`. All users and identities must log in again. | ## Best practices - Keep access tokens short-lived (minutes to hours) and rely on refresh tokens for long sessions. - Store access tokens in memory in browsers, and let the refresh cookie survive reloads. - Never put tokens in URLs, except for WebSocket connections that can't send headers. - Rotate `passport-secret` only as an emergency measure, because it signs everyone out. --- # API keys > Create API keys for servers, functions, scripts and CI, attach policies to them, and rotate them safely. An API key is a static credential for machines. Use it from servers, functions, scripts, CI pipelines and the CLI. ```http Authorization: APIKEY cosc0XtrpGVIzKPP4Q1tvR9X5mJZRdta ``` ![The API keys page in the panel's Access Management section](https://docs.spicaengine.com/screenshots/panel/api-key.webp) ## Create a key ```bash curl -X POST https://api.example.com/api/passport/apikey \ -H "Authorization: IDENTITY " -H "Content-Type: application/json" \ -d '{"name": "Website", "description": "Server-side rendering of the public site", "active": true}' ``` ```json { "name": "Website", "description": "Server-side rendering of the public site", "active": true, "key": "cosc0XtrpGVIzKPP4Q1tvR9X5mJZRdta", "policies": [], "_id": "6b0b1afaa5611972c29c263c" } ``` A new key has no policies. Attach the ones it needs: ```bash curl -X PUT https://api.example.com/api/passport/apikey//policy/BucketReadOnlyAccess \ -H "Authorization: IDENTITY " ``` ## Manage keys | Endpoint | Action | | ---------------------------------------------- | ------------------------------- | | `GET /passport/apikey` | `passport:apikey:index` | | `GET /passport/apikey/:id` | `passport:apikey:show` | | `POST /passport/apikey` | `passport:apikey:create` | | `PUT /passport/apikey/:id` | `passport:apikey:update` | | `DELETE /passport/apikey/:id` | `passport:apikey:delete` | | `PUT /passport/apikey/:id/policy/:policyId` | `passport:apikey:policy:add` | | `DELETE /passport/apikey/:id/policy/:policyId` | `passport:apikey:policy:remove` | Set `active` to `false` to suspend a key without deleting it. ## API keys and rules API keys are checked against their policies only. [Bucket rules](https://docs.spicaengine.com/buckets/rules) don't apply to them, so a key that can read a bucket sees every document in it, drafts included. > **Danger: Don't ship keys to clients** > > Anything in a browser or mobile app can be extracted. Never put an API key with write access, or with read access to private data, in client code. Use user tokens in clients and keep keys on the server. ## Good practices - **One key per consumer.** Create separate keys for the website, each function, CI, every integration and every AI agent using the [MCP server](https://docs.spicaengine.com/ai/mcp-server), so you can revoke one without breaking the others. - **Least privilege.** Prefer [custom policies](https://docs.spicaengine.com/auth/policies) limited to the buckets and actions a consumer uses over the `*FullAccess` policies. - **Store keys as secrets** in functions, and as protected variables in CI. - **Rotate regularly.** Create a new key with the same policies, deploy it, then deactivate and delete the old one. ## Keys for the CLI and CI The [CLI](https://docs.spicaengine.com/cli/contexts) authenticates with an API key. Give the key used by `spica apply` the full-access policies of the modules you manage as code: `BucketFullAccess`, `FunctionFullAccess`, `PolicyFullAccess`, `EnvVarFullAccess` and `SecretFullAccess`. --- # Policies > Write policies that grant identities, users and API keys exactly the actions and resources they need, and use the built-in policies. A policy is a named list of statements. Every statement allows one **action** in one **module**, optionally limited to some **resources**. Policies are attached to identities, users and API keys, and a request is allowed when at least one attached statement matches it. ```json { "name": "Blog Reader", "description": "Read published blog posts", "statement": [ { "action": "bucket:data:index", "module": "bucket:data", "resource": {"include": ["6b0b1968a5611972c29c25f7"], "exclude": []} }, { "action": "bucket:data:show", "module": "bucket:data", "resource": {"include": ["6b0b1968a5611972c29c25f7"], "exclude": []} } ] } ``` ![The policies page listing built-in full access and read only policies](https://docs.spicaengine.com/screenshots/panel/policy.webp) ## Statements | Field | Description | | ---------- | --------------------------------------------------------------------------------------------------------- | | `action` | The operation, such as `bucket:data:index`. | | `module` | The module the action belongs to, such as `bucket:data`. | | `resource` | Optional. `include` and `exclude` lists of resource ids. Leave it out for actions that have no resources. | ### Resources - `"*"` matches every resource. - A resource with several parts is written with `/`, for example `/` for `function:invoke`. - `exclude` removes resources from the `include` list. When `exclude` is used, every `include` entry must end with `*`. ```json {"include": ["*"], "exclude": ["6b0b19cea5611972c29c260f"]} ``` A statement whose resource doesn't fit the action's format makes requests fail with `409` and a message such as `Policy "Blog Reader" contains a statement [0] whose resource does not match the resource definition. Expected 1 arguments.` ## Actions by module | Module | Actions | Resource | | ---------------------------------------------------------------------------- | ------------------------------------------------------------------ | ---------------------------- | | `bucket` | `index`, `show`, `create`, `update`, `delete`, `stream` | Bucket id | | `bucket:data` | `index`, `show`, `create`, `update`, `delete`, `stream`, `profile` | Bucket id | | `function` | `index`, `show`, `create`, `update`, `delete`, `stream` | Function id | | `function:invoke` | `function:invoke` | `/` | | `function:logs` | `index`, `delete` | | | `function:env-var`, `function:secret` | `inject`, `eject` | | | `env-var`, `secret` | `index`, `show`, `create`, `update`, `delete`, `stream` | Id | | `storage` | `index`, `browse`, `show`, `create`, `update`, `delete` | Object id or name | | `passport:identity` | `index`, `show`, `profile`, `create`, `update`, `delete`, `stream` | Identity id | | `passport:identity:policy`, `passport:user:policy`, `passport:apikey:policy` | `add`, `remove` | | | `passport:user` | `index`, `show`, `profile`, `create`, `update`, `delete`, `stream` | User id | | `passport:apikey` | `index`, `show`, `create`, `update`, `delete`, `stream` | API key id | | `passport:policy` | `index`, `show`, `create`, `update`, `delete`, `stream` | Policy id | | `passport:strategy` | `index`, `show`, `insert`, `update`, `delete` | | | `passport:refresh-token` | `index`, `show`, `update`, `delete`, `stream` | | | `dashboard` | `index`, `show`, `create`, `update`, `delete`, `stream` | Dashboard id | | `webhook`, `webhook:logs` | `index`, `show`, `create`, `update`, `delete` / `index`, `delete` | | | `activity` | `index`, `delete` | | | `asset` | `index`, `show`, `install`, `export`, `download`, `delete` | | | `preference` | `show`, `update` | Scope, such as `bucket` | | `config` | `index`, `show`, `update` | | | `status` | `index`, `show` | | Actions are written with their module prefix, for example `passport:user:update`. `GET /passport/identity/statements` returns every statement that applies to the caller. ## Built-in policies Every module has a full access and a read-only policy. Their ids are their names, and they can't be changed. | Policy | Grants | | ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------ | | `ActivityFullAccess`, `ActivityReadOnlyAccess` | Activity stream | | `ApiKeyFullAccess`, `ApiKeyReadOnlyAccess` | API keys | | `AssetFullAccess`, `AssetReadOnlyAccess` | Assets | | `BucketFullAccess`, `BucketReadOnlyAccess` | Bucket schemas and data | | `ConfigFullAccess`, `ConfigReadOnlyAccess` | Configuration | | `DashboardFullAccess`, `DashboardReadOnlyAccess` | Dashboards | | `EnvVarFullAccess`, `EnvVarReadOnlyAccess` | Environment variables | | `FunctionFullAccess`, `FunctionReadOnlyAccess` | Functions, logs and invocation. Read-only also reads env vars; full access also manages env vars and secrets | | `IdentityFullAccess`, `IdentityReadOnlyAccess` | Identities | | `PassportFullAccess`, `PassportReadOnlyAccess` | Identities, strategies, API keys, policies, refresh tokens and users | | `PolicyFullAccess`, `PolicyReadOnlyAccess` | Policies | | `PreferenceFullAccess`, `PreferenceReadOnlyAccess` | Preferences | | `RefreshTokenFullAccess`, `RefreshTokenReadOnlyAccess` | Refresh tokens | | `SecretFullAccess`, `SecretReadOnlyAccess` | Secrets | | `StatusFullAccess` | Status and usage | | `StorageFullAccess`, `StorageReadOnlyAccess` | Storage | | `StrategyFullAccess`, `StrategyReadOnlyAccess` | Login strategies | | `UserFullAccess`, `UserReadOnlyAccess` | Users | | `WebhookFullAccess`, `WebhookReadOnlyAccess` | Webhooks | ## Manage policies | Endpoint | Action | | ----------------------------- | ------------------------ | | `GET /passport/policy` | `passport:policy:index` | | `GET /passport/policy/:id` | `passport:policy:show` | | `POST /passport/policy` | `passport:policy:create` | | `PUT /passport/policy/:id` | `passport:policy:update` | | `DELETE /passport/policy/:id` | `passport:policy:delete` | Changes take effect immediately for everyone the policy is attached to, without new tokens. ## Examples ### Example: content editor Lets editors manage the entries of two content buckets and upload images, without touching schemas, functions or users: ```json { "name": "Content Editor", "description": "Manage posts and authors, upload media", "statement": [ {"action": "bucket:index", "module": "bucket", "resource": {"include": ["*"], "exclude": []}}, {"action": "bucket:show", "module": "bucket", "resource": {"include": ["", ""], "exclude": []}}, {"action": "bucket:data:index", "module": "bucket:data", "resource": {"include": ["", ""], "exclude": []}}, {"action": "bucket:data:show", "module": "bucket:data", "resource": {"include": ["", ""], "exclude": []}}, {"action": "bucket:data:create", "module": "bucket:data", "resource": {"include": ["", ""], "exclude": []}}, {"action": "bucket:data:update", "module": "bucket:data", "resource": {"include": ["", ""], "exclude": []}}, {"action": "bucket:data:delete", "module": "bucket:data", "resource": {"include": ["", ""], "exclude": []}}, {"action": "preference:show", "module": "preference", "resource": {"include": ["bucket"], "exclude": []}} ] } ``` Combine it with `StorageFullAccess` so that editors can upload images. ### Example: everything except one bucket ```json { "name": "All Data Except Customers", "description": "Read every bucket but customers", "statement": [ {"action": "bucket:data:index", "module": "bucket:data", "resource": {"include": ["*"], "exclude": [""]}} ] } ``` ### Example: call one HTTP function For HTTP triggers with `authorize: true`: ```json { "name": "Order API", "description": "Create orders", "statement": [ {"action": "function:invoke", "module": "function:invoke", "resource": {"include": ["/createOrder"], "exclude": []}} ] } ``` ## Designing policies - Start from the built-in read-only policies and add write access deliberately. - Create policies per role ("Content Editor", "Support") instead of per person. - Give API keys their own narrow policies. - For users, combine a policy that opens the endpoints with [bucket rules](https://docs.spicaengine.com/buckets/rules) that filter the documents. - Keep policies in git with the [CLI](https://docs.spicaengine.com/cli/resources-as-code), so changes are reviewed. --- # Login strategies > Let identities sign in with SAML single sign-on, and users with Google, GitHub, Facebook, Okta, Auth0 or any custom OAuth 2.0 provider. Strategies add external login methods: | Type | For | Providers | | ------- | ---------- | ----------------------------------------------------------- | | `saml` | Identities | Any SAML 2.0 identity provider | | `oauth` | Users | `google`, `github`, `facebook`, `okta`, `auth0` or `custom` | Manage strategies in **Access Management → Strategies** or with `/passport/strategy` (`passport:strategy:*` actions). ![The strategies page in Access Management](https://docs.spicaengine.com/screenshots/panel/strategy.webp) ## OAuth for users ### Create a strategy For the built-in providers, provide your OAuth application's credentials: ```bash curl -X POST https://api.example.com/api/passport/strategy \ -H "Authorization: IDENTITY " -H "Content-Type: application/json" \ -d '{ "type": "oauth", "icon": "login", "options": {"idp": "google", "client_id": "", "client_secret": ""} }' ``` `okta` and `auth0` also need `domain`, the domain of your tenant. In your provider's console, register this redirect URI: ```text /passport/user/strategy//complete ``` ### Login flow The login is completed by the API, so your client only needs the strategy id: 1. **Get the provider URL** ```bash curl https://api.example.com/api/passport/user/strategy//url ``` ```json {"url": "https://accounts.google.com/o/oauth2/v2/auth?client_id=...&state=...", "state": "f3b1..."} ``` 2. **Wait for the result and send the user to the provider** Start a login request with the `state`, then open `url` in a popup or a new tab. The login request stays open until the user finishes, for up to 60 seconds: ```javascript const {url, state} = await fetch(`${API}/passport/user/strategy/${strategyId}/url`).then(r => r.json()); const pending = fetch(`${API}/passport/login`, { method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify({state}) }).then(r => r.json()); window.open(url, "_blank"); const {token} = await pending; ``` 3. **Use the token** The response is a normal user login: `{"scheme": "USER", "token": "..."}`. The first login creates the user. Its username is taken from the provider's response (`upn`, `id`, `name_id` or `email`), and its `signUpStrategy` records the strategy. ### Custom OAuth providers Describe each step of the OAuth flow: ```json { "type": "oauth", "name": "my-sso", "title": "Company SSO", "options": { "idp": "custom", "code": { "base_url": "https://sso.example.com/oauth/authorize", "params": {"client_id": "", "response_type": "code", "scope": "openid email"}, "method": "get" }, "access_token": { "base_url": "https://sso.example.com/oauth/token", "params": {"client_id": "", "client_secret": "", "grant_type": "authorization_code"}, "method": "post" }, "identifier": { "base_url": "https://sso.example.com/oauth/userinfo", "method": "get" }, "attributes": {"email": "email", "name": "name"} } } ``` | Field | Description | | -------------- | ------------------------------------------------------------------------------------------------------------------- | | `code` | Where users authorize. Spica adds `redirect_uri` and `state`. | | `access_token` | Where the code is exchanged for an access token. | | `identifier` | Where user information is fetched with the access token. | | `attributes` | Maps user attributes to top-level fields of the user information response. They are stored, encrypted, on the user. | Each step accepts `base_url`, `params`, `headers` and `method` (`get` or `post`). ## SAML for identities SAML lets your team sign in to the panel with your company's identity provider. ```json { "type": "saml", "name": "okta-saml", "title": "Sign in with Okta", "icon": "login", "options": { "ip": { "login_url": "https://example.okta.com/app/.../sso/saml", "logout_url": "https://example.okta.com/login/signout", "certificate": "-----BEGIN CERTIFICATE-----..." } } } ``` | Field | Description | | ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `options.ip.login_url` | **Required.** The identity provider's SSO URL. | | `options.ip.certificate` | **Required.** The identity provider's signing certificate. | | `options.ip.logout_url` | Optional logout URL. | | `options.sp` | Optional service provider `certificate` and `private_key`. When left out, Spica creates a self-signed certificate valid for `--passport-saml-certificate-ttl` seconds. | Configure your identity provider with Spica's service provider metadata: ```text /passport/identity/strategy//metadata ``` and the assertion consumer URL: ```text /passport/identity/strategy//complete ``` The panel shows SAML strategies on its login page. Programmatically, the flow mirrors OAuth: `GET /passport/identity/strategy//url`, then `POST /passport/identify` with `{"state": ...}`. > **Note** > > Identities that sign in through SAML still need policies. Attach them after the first login, or manage identities through an automation that assigns policies by group. --- # Two-factor authentication > Protect identity and user accounts with time-based one-time passwords from apps such as Google Authenticator or 1Password. Spica supports two-factor authentication with time-based one-time passwords (TOTP). After a user or identity enables it, logging in takes their password and a 6-digit code from an authenticator app. ```bash curl https://api.example.com/api/passport/identity/factors -H "Authorization: IDENTITY " ``` ```json [{"type": "totp", "title": "Time based One Time Password", "description": "Verification with time based one time passwords which are usually generated by apps like Google Auth, Duo etc.", "config": {}}] ``` ## Enable it The examples use identities. For users, replace `/passport/identity/` with `/passport/user/`. Users can enable it on their own account with their own token. 1. **Start the setup** ```bash curl -X POST https://api.example.com/api/passport/identity//start-factor-verification \ -H "Authorization: IDENTITY " -H "Content-Type: application/json" \ -d '{"type": "totp", "config": {}}' ``` ```json {"challenge": "data:image/png;base64,iVBORw0KGgo...", "answerUrl": "passport/identity//complete-factor-verification"} ``` `challenge` is a QR code image. Show it to the person and let them scan it with their authenticator app. 2. **Confirm with a code** ```bash curl -X POST https://api.example.com/api/passport/identity//complete-factor-verification \ -H "Authorization: IDENTITY " -H "Content-Type: application/json" \ -d '{"answer": "123456"}' ``` The setup must be completed within 5 minutes of starting it. ## Log in with a second factor When two-factor authentication is on, the login response is a challenge instead of a token: ```bash curl -X POST https://api.example.com/api/passport/identify \ -H "Content-Type: application/json" \ -d '{"identifier": "spica", "password": "spica"}' ``` ```json {"challenge": "Please enter the 6 digit code", "answerUrl": "passport/identify//factor-authentication"} ``` Send the code to `answerUrl` to receive the token: ```bash curl -X POST https://api.example.com/api/passport/identify//factor-authentication \ -H "Content-Type: application/json" \ -d '{"answer": "123456"}' ``` For users the endpoints are `POST /passport/login` and `POST /passport/login//factor-authentication`. With the [identity devkit](https://docs.spicaengine.com/devkit/identity), `login` returns either a token or a challenge, and `isChallenge` tells them apart. ## Disable it ```bash curl -X DELETE https://api.example.com/api/passport/identity//factors \ -H "Authorization: IDENTITY " ``` > **Tip** > > Require two-factor authentication for every identity with full access. It's the account that can read your secrets and change your functions. --- # Password & login security > Enforce password rules, prevent password reuse, lock accounts after failed logins and rate-limit sensitive user endpoints. ## Password policy Password rules for users and identities live in the [configuration module](https://docs.spicaengine.com/platform/config), under the `user` and `identity` modules: ```bash curl -X PUT https://api.example.com/api/config/user \ -H "Authorization: IDENTITY " -H "Content-Type: application/json" \ -d '{"password": {"minLength": 10, "minLowercase": 1, "minUppercase": 1, "minNumber": 1, "minSpecialCharacter": 1}}' ``` | Rule | Description | | --------------------- | ----------------------------- | | `minLength` | Minimum number of characters. | | `minLowercase` | Minimum lowercase letters. | | `minUppercase` | Minimum uppercase letters. | | `minNumber` | Minimum digits. | | `minSpecialCharacter` | Minimum special characters. | Passwords that break the rules are rejected when an account is created or its password changes: ```json {"message": ".password must NOT have fewer than 10 characters", "error": "validation failed", "statusCode": 400} ``` > **Note** > > `PUT /config/:module` replaces the whole module configuration. Send every setting of the module, not only the one you change. ## Password history Prevent people from reusing their recent passwords: | Option | Default | | -------------------------------------------- | --------- | | `--passport-identity-password-history-limit` | `0` (off) | | `--passport-user-password-history-limit` | `0` (off) | With a limit of `5`, a new password can't be any of the last five. ## Lockout after failed logins | Option | Default | Description | | ---------------------------------------------------------------- | --------- | -------------------------------------------- | | `--passport-identity-failed-login-attempt-limit` | `0` (off) | Failed logins before identities are blocked. | | `--passport-identity-block-duration-after-failed-login-attempts` | `0` | Minutes the block lasts. | | `--passport-user-failed-login-attempt-limit` | `0` (off) | Failed logins before users are blocked. | | `--passport-user-block-duration-after-failed-login-attempts` | `0` | Minutes the block lasts. | For example, `--passport-user-failed-login-attempt-limit=5 --passport-user-block-duration-after-failed-login-attempts=15` blocks a user for 15 minutes after five wrong passwords. ## Rate limits User endpoints that attackers like to hammer have their own rate limits, set in the `user` configuration: ```json { "rateLimits": { "login": {"limit": 10, "ttl": 60}, "forgotPassword": {"limit": 5, "ttl": 300}, "providerVerification": {"limit": 5, "ttl": 300}, "refreshToken": {"limit": 30, "ttl": 60}, "createUser": {"limit": 20, "ttl": 60} } } ``` `limit` is the number of requests allowed within `ttl` **seconds**. | Key | Applies to | | ---------------------- | ------------------------------------------------------ | | `login` | User login (`/passport/login`) and passwordless login. | | `forgotPassword` | Password reset start and verify. | | `providerVerification` | Email and phone verification. | | `refreshToken` | User session refresh. | | `createUser` | `POST /passport/user`. | For your own HTTP functions, use the trigger's [`rateLimit`](https://docs.spicaengine.com/functions/http#rate-limiting) option. ## Account and instance limits | Option | Effect | | ---------------------------------------------- | -------------------------------------------------------- | | `--passport-user-limit` | Maximum number of users. | | `--passport-identity-limit` | Maximum number of identities. | | `--passport-user-verification-code-expires-in` | Lifetime of verification codes in seconds (default 300). | ## Checklist - Change the default identity's password, or remove the default identity. - Turn on two-factor authentication for identities with full access. - Set a password policy for users and identities. - Enable lockout and rate limits before you open sign-up to the public. - Keep access tokens short-lived and use refresh tokens. - Serve the API over HTTPS only. - Review identities, API keys and refresh tokens regularly, and remove what's unused. --- # Storage > Upload, organize, serve and protect files with the storage module, on local disk, Amazon S3 or Google Cloud Storage, including resumable uploads. The storage module stores files ("objects") and their metadata. Objects can be referenced from bucket properties of type `storage`, organized into folders, protected with policies and served with HTTP caching. ![The storage browser in the panel with an images folder and two files](https://docs.spicaengine.com/screenshots/panel/storage.webp) ## Objects ```json { "_id": "6b0b1b47a5611972c29c2648", "name": "cover.png", "content": {"type": "image/png", "size": 29159}, "created_at": "2026-11-28T18:19:51.477Z", "updated_at": "2026-11-28T18:19:51.477Z", "url": "https://api.example.com/api/storage/cover.png/view" } ``` | Field | Description | | -------------- | -------------------------------------------------------------------------------------------- | | `name` | Unique name. Slashes create folders: `images/2026/cover.png`. | | `content.type` | MIME type. | | `content.size` | Size in bytes. | | `url` | Where the content can be downloaded. Depends on the [storage strategy](#storage-strategies). | ## Upload **Multipart** ```bash curl -X POST https://api.example.com/api/storage \ -H "Authorization: APIKEY " \ -F "files=@cover.png;type=image/png" ``` **JSON** Send base64-encoded content: ```bash curl -X POST https://api.example.com/api/storage \ -H "Authorization: APIKEY " -H "Content-Type: application/json" \ -d '[{"name": "hello.txt", "content": {"type": "text/plain", "data": "SGVsbG8gU3BpY2E="}}]' ``` **Devkit** ```typescript import * as Storage from "@spica-devkit/storage"; Storage.initialize({apikey: process.env.SPICA_API_KEY, publicUrl: "https://api.example.com/api"}); const [object] = await Storage.insertMany([ {name: "hello.txt", contentType: "text/plain", data: Buffer.from("Hello Spica")} ]); ``` Both forms accept several files in one request and return an array of objects. ### Folders A folder is an empty object whose name ends with `/`. Create the folder before uploading into it: ```json [{"name": "images/", "content": {"type": "", "data": ""}}] ``` ```json [{"name": "images/banner.png", "content": {"type": "image/png", "data": ""}}] ``` Browse a folder with `GET /storage/browse?path=images/`. ## Resumable uploads Large files and unreliable networks are better served by resumable uploads. Spica implements the [tus protocol](https://tus.io) at `/storage/resumable`. Send the file name and type as `filename` and `filetype` metadata: ```javascript import * as tus from "tus-js-client"; const upload = new tus.Upload(file, { endpoint: "https://api.example.com/api/storage/resumable", headers: {Authorization: `APIKEY ${key}`}, metadata: {filename: file.name, filetype: file.type}, onProgress: (sent, total) => console.log(`${Math.round((sent / total) * 100)}%`), onSuccess: () => console.log("Uploaded") }); upload.start(); ``` Unfinished uploads are discarded after `--resumable-upload-expires-in` milliseconds (two days by default). ## Download `GET /storage/:idOrName/view` The response streams the content with `Content-Type`, `ETag` and caching headers, and supports `Range`, `If-None-Match` and `If-Modified-Since`. Requests need an `Authorization` header. ```bash curl https://api.example.com/api/storage/cover.png/view -H "Authorization: APIKEY " -o cover.png ``` `GET /storage/:idOrName` returns the metadata only. > **Note: Serving files publicly** > > On the `default` strategy, downloads always need credentials, so browsers can't load `url` directly in an `` tag. For public assets, use the `awss3` or `gcloud` strategy with a public bucket or a CDN in front of it, or serve files through an HTTP function. With the API, fetch the file with credentials and display it as a blob. ## List, rename, replace and delete | Endpoint | Action | Purpose | | --------------------------- | ---------------- | --------------------------------------------------------------------------------------------- | | `GET /storage` | `storage:index` | List objects. Accepts `filter`, `sort`, `limit`, `skip`, `paginate`. | | `GET /storage/browse?path=` | `storage:browse` | List one folder. | | `PATCH /storage/:id` | `storage:update` | Rename: `{"name": "new-name.png"}`. | | `PUT /storage/:id` | `storage:update` | Replace the content. | | `DELETE /storage/:idOrName` | `storage:delete` | Delete one object. | | `DELETE /storage` | `storage:delete` | Delete several: body `["", "images/old.png"]`. Nothing is deleted unless all are allowed. | ```bash curl -G https://api.example.com/api/storage -H "Authorization: APIKEY " \ --data-urlencode 'filter={"name": "hello.txt"}' --data-urlencode "paginate=true" ``` ```json {"meta": {"total": 1}, "data": [{"_id": "6b0b1b47a5611972c29c264a", "name": "hello.txt", "content": {"type": "text/plain", "size": 11}}]} ``` ## Access control Storage endpoints accept identities and API keys. Use [policies](https://docs.spicaengine.com/auth/policies) to control access, down to folders: storage statements match object ids and names, so an exclusion such as `private/*` hides a folder. ```json { "name": "Public Media", "description": "Everything except the private folder", "statement": [ {"action": "storage:show", "module": "storage", "resource": {"include": ["*"], "exclude": ["private/*"]}} ] } ``` To let end users upload files, accept the upload in an [HTTP function](https://docs.spicaengine.com/recipes/s3-media-uploads) that checks the user's token and stores the file with an API key. ## Storage strategies Choose where content is kept with `--storage-strategy`: | Strategy | Content lives in | Object `url` | Options | | --------- | ------------------------------------------------------------ | ---------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | | `default` | `--persistent-path/--default-storage-path` on the API's disk | `/storage//view` | `--default-storage-path` (relative, default `storage`), `--default-storage-public-url` (defaults to `--public-url`) | | `awss3` | An S3 bucket | `https://.s3..amazonaws.com/` | `--awss3-bucket-name`, `--awss3-credentials-path` (optional, otherwise the AWS default credential chain such as EKS IRSA) | | `gcloud` | A Google Cloud Storage bucket | `https://storage.googleapis.com/download/storage/v1/b//o/?alt=media` | `--gcloud-bucket-name`, `--gcloud-service-account-path` | With several API replicas, use `awss3` or `gcloud`, or a shared volume, so that every replica sees the same files. ## Limits | Option | Default | Effect | | ----------------------------- | ------- | ---------------------------------------- | | `--storage-object-size-limit` | `35` | Maximum size of one object in MiB. | | `--storage-total-size-limit` | | Maximum total size of all objects in MB. | Behind a proxy, also raise the proxy's body size limit. The Helm chart sets `nginx.ingress.kubernetes.io/proxy-body-size` for this. ## Referencing files from buckets A bucket property of type `storage` stores the object's URL. In the panel, editors pick or upload the file. Over the API, upload the file first and write its `url` into the document. --- # Environment variables & secrets > The modules that store configuration values and encrypted credentials for functions, and the endpoints that manage them. Environment variables and secrets are stored once and attached to the functions that use them. For how functions read them and how placeholders work, see [Functions → Env vars & secrets](https://docs.spicaengine.com/functions/environment). ![The secrets and variables page in the panel](https://docs.spicaengine.com/screenshots/panel/secrets-and-variables.webp) ## Environment variables | Endpoint | Action | | --------------------- | ---------------- | | `GET /env-var` | `env-var:index` | | `GET /env-var/:id` | `env-var:show` | | `POST /env-var` | `env-var:create` | | `PUT /env-var/:id` | `env-var:update` | | `DELETE /env-var/:id` | `env-var:delete` | ```json {"key": "SITE_URL", "value": "https://blog.example.com"} ``` ## Secrets | Endpoint | Action | | -------------------- | --------------- | | `GET /secret` | `secret:index` | | `GET /secret/:id` | `secret:show` | | `POST /secret` | `secret:create` | | `PUT /secret/:id` | `secret:update` | | `DELETE /secret/:id` | `secret:delete` | Secret values are encrypted with `--secret-module-encryption-secret` (derived from the master key when not set). The API never returns them: ```json {"_id": "6b0b1a93a5611972c29c2623", "key": "STRIPE_KEY", "salt": "16745bff...", "value_hash": "f7a2bd56...", "updated_at": "2026-11-28T18:16:51.516Z"} ``` `value_hash` is a salted hash of the value, so tools can compare values without reading them. ## Per-environment values Keep the same keys in every environment and change only the values. With the CLI, values for each context are stored outside git in `.spica/.env`, or provided as `SPICA_VALUE_` environment variables in CI. See [Values per environment](https://docs.spicaengine.com/cli/values). --- # Webhooks > Send an HTTP POST to any URL when documents change, with a body built from a Handlebars template, and inspect every delivery. A webhook posts to a URL whenever a change happens in a collection, for example when a document is inserted into a bucket. Use webhooks to notify Slack, start a CI build or call another service, without writing a function. ![A webhook in the panel, showing its trigger, active state, body template and delivery logs](https://docs.spicaengine.com/screenshots/panel/webhook.webp) ## Create a webhook ```bash curl -X POST https://api.example.com/api/webhook \ -H "Authorization: IDENTITY " -H "Content-Type: application/json" \ -d '{ "title": "Notify Slack on new post", "url": "https://hooks.slack.com/services/T000/B000/XXXX", "body": "{\"text\": \"New post: {{document.slug}}\"}", "trigger": { "name": "database", "active": true, "options": {"collection": "bucket_6b0b1968a5611972c29c25f7", "type": "INSERT"} } }' ``` | Field | Description | | ---------------------------- | ------------------------------------------------------------------------ | | `title` | Name shown in the panel. | | `url` | Where to send the request. | | `body` | A [Handlebars](https://handlebarsjs.com/) template for the request body. | | `trigger.name` | Always `database`. | | `trigger.active` | Pause the webhook with `false`. | | `trigger.options.collection` | The collection to watch. Bucket data is stored in `bucket_`. | | `trigger.options.type` | `INSERT`, `UPDATE`, `REPLACE` or `DELETE`. | `GET /webhook/collections` lists the collections you can watch, with readable names for buckets: ```json [{"id": "bucket_6b0b1968a5611972c29c25f7", "slug": "Posts"}, {"id": "identity", "slug": "identity"}] ``` ## The request Spica sends a `POST` with `Content-Type: application/json` and `User-Agent: Spica/Webhooks; (https://spicaengine.com/docs/guide/webhook)`. The body template is rendered with: | Variable | Contents | | ------------- | --------------------------------------------------------- | | `type` | The operation: `insert`, `update`, `replace` or `delete`. | | `documentKey` | The id of the document. | | `document` | The document after the change, or before it for deletes. | Use the `toJSON` helper with triple braces to embed objects: ```handlebars {"event": "{{type}}", "id": "{{documentKey}}", "post": {{{ toJSON document }}}} ``` Templates are rendered in strict mode: referencing a missing property fails the delivery and records the error. ## Delivery logs Every delivery is logged with the request, the response status and body, and whether it succeeded (status below 400). | Endpoint | Description | | -------------------------------- | ------------------------------------------------------------------------------------------ | | `GET /webhook/logs?webhook=` | Logs of a webhook. Filter with `succeed=true` or `false`, `begin`, `end`, `skip`, `limit`. | | `DELETE /webhook/logs/:id` | Delete one log entry. | | `DELETE /webhook/logs` | Clear logs. | ## Manage webhooks | Endpoint | Action | | --------------------- | ---------------- | | `GET /webhook` | `webhook:index` | | `GET /webhook/:id` | `webhook:show` | | `POST /webhook` | `webhook:create` | | `PUT /webhook/:id` | `webhook:update` | | `DELETE /webhook/:id` | `webhook:delete` | ## Webhooks or functions? | Use a webhook when | Use a [function](https://docs.spicaengine.com/functions/bucket-and-database) when | | ---------------------------------------- | --------------------------------------------------------------------------------- | | You only forward the change to a URL. | You need logic, conditions or several calls. | | The receiver accepts a simple JSON body. | You need authentication beyond a URL token, retries or transformations. | Webhooks are fire-and-forget: a failed delivery is logged but not retried. --- # Dashboards > Build dashboards for your team in the panel, with charts, tables, statistics and forms fed by your own HTTP functions. A dashboard is a page in the panel made of components. Each component loads JSON from a URL, usually an [HTTP function](https://docs.spicaengine.com/functions/http), and renders it as a chart, a table, a statistic or a form. Dashboards are the quickest way to give business users KPIs and reports without building a separate admin app. ![A dashboard with a line chart of daily views and a statistic tile for published posts](https://docs.spicaengine.com/screenshots/panel/dashboard.webp) ## Create a dashboard ```json { "name": "Blog overview", "icon": "insights", "components": [ {"name": "Daily views", "url": "https://api.example.com/api/fn-execute/stats/views", "type": "line", "ratio": "2/2"}, {"name": "Published posts", "url": "https://api.example.com/api/fn-execute/stats/posts", "type": "statistic", "ratio": "1/1"} ] } ``` | Field | Description | | -------------------- | ----------------------------------------------------------- | | `name` | **Required.** Shown in the panel's dashboard list. | | `icon` | A Material icon name. | | `components[].name` | Title of the component. | | `components[].url` | URL that returns the component's data with a `GET` request. | | `components[].type` | How the data is rendered. | | `components[].ratio` | Size on the grid, such as `1/1` or `2/2` (default). | Create dashboards in the panel or with `POST /dashboard` (`dashboard:create`). Manage them with `GET`, `PUT` and `DELETE` on `/dashboard/:id`. ## Component types and data ### Charts Types: `line`, `bar`, `radar`, `pie`, `doughnut`, `polarArea`, `bubble`, `scatter`. The data follows [Chart.js](https://www.chartjs.org/): ```javascript export function views() { return { title: "Daily views", options: {legend: {display: true}, responsive: true}, labels: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"], datasets: [{data: [120, 190, 170, 240, 310, 280, 350], label: "Views"}], legend: true }; } ``` `pie`, `doughnut` and `polarArea` take `labels` and a `data` array instead of `datasets`. `bubble` and `scatter` take points such as `{"x": 10, "y": 5, "r": 8}` in their datasets. ### Statistic A single number with an optional change indicator: ```javascript export function posts() { return {title: "Published posts", value: 42, difference: 12, icon: "article", iconBg: "#36369c", iconColor: "white"}; } ``` `difference` is shown as a percentage, green when positive and red when negative. ### Table ```javascript export function topAuthors() { return { title: "Top authors", data: [ {name: "Ada Lovelace", posts: 12}, {name: "Alan Turing", posts: 9} ], displayedColumns: ["name", "posts"] }; } ``` When `displayedColumns` is left out, the keys of the first row are used. ### Card A small form that sends its values to a URL, useful for operational actions such as "resend invoice": ```json { "title": "Resend invoice", "description": "Send the invoice email of an order again.", "inputs": [{"key": "orderId", "type": "string", "value": "", "title": "Order id"}], "button": {"color": "primary", "target": "https://api.example.com/api/fn-execute/invoices/resend", "method": "post", "title": "Send"} } ``` ## Securing dashboard endpoints The panel calls component URLs with the logged-in identity's token. Protect the functions behind them with `authenticate: ["IDENTITY"]` so that only your team can load the data: ```yaml triggers: views: type: http active: true options: method: Get path: /stats/views authenticate: [IDENTITY] ``` ## Tips - Pre-aggregate expensive numbers on a [schedule](https://docs.spicaengine.com/functions/schedule) and store them in a bucket. Dashboard functions then only read the result. - Keep one function per dashboard and one handler per component. - Give business users `DashboardReadOnlyAccess` and access only to what the dashboards need. --- # Activity stream > See who created, changed or deleted what, when, across buckets, functions, storage, identities and the rest of the API. The activity stream records every write made through the API: who made it, what kind of change it was and which resource it touched. Use it for audits, support investigations and "who changed this?" questions. ![The activities page in the panel listing changes by identity, action and resource](https://docs.spicaengine.com/screenshots/panel/activity.webp) ## Records ```json { "_id": "6b0b1ba5a5611972c29c2659", "identifier": "spica", "action": 1, "resource": ["bucket", "6b0b1968a5611972c29c25f7", "data", "6b0b1ba5a5611972c29c2658"], "created_at": "2026-11-28T18:21:25.242Z" } ``` | Field | Description | | -------------------------- | ---------------------------------------------------------------------------------- | | `identifier` or `username` | The identity or user who made the change. | | `action` | `1` insert (POST), `2` replace (PUT), `3` delete, `4` patch. | | `resource` | Path of the affected resource, for example bucket, bucket id, `data`, document id. | | `created_at` | When it happened. | ## Query activities `GET /activity` | Query parameter | Description | | ------------------------ | -------------------------------------------------------------------------- | | `identifier`, `username` | Who made the change. | | `action` | One or more action numbers. | | `resource` | Resource path segments, for example `resource=bucket&resource=`. | | `documentId` | One or more document ids. | | `begin`, `end` | Time range. | | `skip`, `limit` | Pagination. | ```bash curl -G https://api.example.com/api/activity -H "Authorization: IDENTITY " \ --data-urlencode "action=3" --data-urlencode "limit=20" ``` Delete records with `DELETE /activity/:id`, or several with `DELETE /activity`. The actions are `activity:index` and `activity:delete`. ## Retention and switching it off - Records expire after `--common-log-lifespan` seconds (30 days by default). - Turn the stream off with `--activity-stream=false`. Under **Access Management → User Activities**, the panel shows the same information for end users. --- # Configuration & preferences > Change runtime settings such as password policies, verification channels and rate limits with the config module, and bucket languages with preferences. Most of Spica is configured with [startup options](https://docs.spicaengine.com/self-hosting/configuration). Settings that you may want to change while the instance runs live in two modules: **config** and **preferences**. ![The configuration page in the panel with User and Identity modules](https://docs.spicaengine.com/screenshots/panel/config.webp) ## Config module Each config module has a JSON schema. List them with `GET /config/schema`: | Module | Settings | | ---------- | ------------------------------------------------------------------------------------------------------------------ | | `user` | Password policy, verification channels, password reset, passwordless login, verification attempts and rate limits. | | `identity` | Password policy. | ### Read and update | Endpoint | Action | Purpose | | --------------------- | --------------- | ----------------------------------------------------- | | `GET /config` | `config:index` | Every stored module configuration. | | `GET /config/schema` | | Schemas of all modules. | | `GET /config/:module` | `config:show` | One module. Returns `404` until it has been set once. | | `PUT /config/:module` | `config:update` | Replace the module's settings. | The body of `PUT` is the settings object itself, and it replaces what was stored before: ```bash curl -X PUT https://api.example.com/api/config/user \ -H "Authorization: IDENTITY " -H "Content-Type: application/json" \ -d '{ "password": {"minLength": 10, "minNumber": 1}, "providerVerificationConfig": [{"provider": "email", "strategy": "Otp"}], "resetPasswordProvider": [{"provider": "email", "strategy": "Otp"}], "passwordlessLogin": {"passwordlessLoginProvider": [{"provider": "email", "strategy": "MagicLink"}]}, "verificationProcessMaxAttempt": 5, "rateLimits": {"login": {"limit": 10, "ttl": 60}} }' ``` ```json {"_id": "6b0b1ad7988a814684c8fec6", "module": "user", "options": {"password": {"minLength": 10, "minNumber": 1}}} ``` ### `user` settings | Setting | Description | | --------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | | `password` | `minLength`, `minLowercase`, `minUppercase`, `minNumber`, `minSpecialCharacter`. | | `providerVerificationConfig` | Channels users can verify: `[{provider: "email" or "phone", strategy: "Otp" or "MagicLink"}]`. | | `resetPasswordProvider` | Channels allowed for password reset. | | `passwordlessLogin.passwordlessLoginProvider` | Channels allowed for passwordless login. | | `verificationProcessMaxAttempt` | Attempts allowed for a verification process. | | `rateLimits` | `login`, `providerVerification`, `forgotPassword`, `refreshToken`, `createUser`, each `{limit, ttl}` with `ttl` in seconds. | See [Users](https://docs.spicaengine.com/auth/users) and [Password & login security](https://docs.spicaengine.com/auth/security) for how these are used. ## Preferences Preferences are smaller, scoped settings. The `bucket` scope holds the languages of [translated properties](https://docs.spicaengine.com/buckets/schema#translations): ```bash curl https://api.example.com/api/preference/bucket -H "Authorization: IDENTITY " ``` ```json {"scope": "bucket", "language": {"available": {"tr_TR": "Turkish", "en_US": "English"}, "default": "en_US"}} ``` Change them with `PUT /preference/bucket`. The actions are `preference:show` and `preference:update`, with the scope as the resource. ```bash curl -X PUT https://api.example.com/api/preference/bucket \ -H "Authorization: IDENTITY " -H "Content-Type: application/json" \ -d '{"scope": "bucket", "language": {"available": {"en_US": "English", "de_DE": "German"}, "default": "en_US"}}' ``` --- # Mailer & SMS > Configure SMTP and Twilio so that Spica can send verification codes, magic links, password resets and passwordless logins by email and SMS. Spica sends email and SMS for the user flows of the [Passport module](https://docs.spicaengine.com/auth/users): email and phone verification, password reset and passwordless login. Configure the channels with startup options. ## Email (SMTP) | Option | Description | | -------------------------------- | ------------------------------------------------------------------------------------------------------------------- | | `--mailer-host` | SMTP server, for example `smtp.sendgrid.net`. | | `--mailer-port` | SMTP port, for example `587`. | | `--mailer-secure` | Use TLS from the start (port `465`). Default `false`, which still upgrades with STARTTLS when the server offers it. | | `--mailer-user`, `--mailer-pass` | SMTP credentials. | | `--mailer-from` | Default sender, for example `"Acme "`. | ```bash --mailer-host=smtp.sendgrid.net --mailer-port=587 \ --mailer-user=apikey --mailer-pass=$SENDGRID_API_KEY \ --mailer-from="Acme " ``` ## SMS (Twilio) | Option | Environment variable | | ---------------------------------- | -------------------- | | `--sms-sender-strategy=twilio` | | | `--twilio-sms-service-account-sid` | `TWILIO_ACCOUNT_SID` | | `--twilio-sms-service-auth-token` | `TWILIO_AUTH_TOKEN` | | `--twilio-sms-service-from-number` | `TWILIO_FROM_NUMBER` | Prefer the environment variables for credentials. The Helm chart reads them from `application.twilioAccountSid`, `application.twilioAuthToken` and `application.twilioFromNumber`. ## What users receive | Strategy | Email | SMS | | ----------- | --------------------------------------------------------------------------- | ------------------------------------------------- | | `Otp` | Subject `Spica verification code`, text `Your verification code is: 123456` | `Your verification code is: 123456` | | `MagicLink` | `Verify your email by clicking this link: ` | `Verify your phone by clicking this link: ` | Magic links point to `/passport/user/verify-magic-link?token=...`, so `--public-url` must be reachable by your users. ## Sending other messages The mailer and SMS sender don't have a public API. To send your own emails or texts, for example order confirmations, call your provider from a [function](https://docs.spicaengine.com/recipes/welcome-email), with its credentials stored as [secrets](https://docs.spicaengine.com/functions/environment). --- # Status & observability > Health checks, usage statistics, access logs, request tracing and the panel's observability pages for running Spica in production. ## Health checks | Endpoint | Auth | Use for | | ------------------- | ---- | ---------------------------------------------------------------------------- | | `GET /status/live` | None | Liveness probes. Answers `{"status": "ok"}` while the process is up. | | `GET /status/ready` | None | Readiness probes. Answers `{"status": "ok"}` when the API can serve traffic. | The Helm chart uses `/status/live` for startup and liveness probes and `/status/ready` for readiness. ## Usage statistics `GET /status` (with `status:index`) reports usage per module: ```json [ {"module": "bucket", "status": {"buckets": {"current": 3, "unit": "count"}, "bucketData": {"current": 6, "unit": "count"}}}, {"module": "storage", "status": {"size": {"current": 0.03, "unit": "mb"}}}, {"module": "api", "status": {"request": {"current": 180, "unit": "count"}, "uploaded": {"current": 0.04, "unit": "mb"}, "downloaded": {"current": 0.15, "unit": "mb"}}}, {"module": "user", "status": {"users": {"current": 1, "unit": "count"}}} ] ``` `GET /status/:module` returns one module. API request counts and sizes are collected while `--http-status-tracking` is on (the default), and records expire after `--common-log-lifespan`. The panel's home page shows the same numbers, including usage against configured limits and traffic over time. ![The panel home page with resource overview, usage limits and traffic charts](https://docs.spicaengine.com/screenshots/panel/home.webp) ## Access logs Log every HTTP request to stdout: | Option | Default | Description | | --------------------------------------- | -------------- | ------------------------------------------------------------------------- | | `--access-logs` | `false` | Turn access logs on. | | `--access-logs-url-filter` | `.*` | Only log URLs matching this regular expression. | | `--access-logs-statuscode-filter` | `.*` | Only log status codes matching this regular expression, for example `^5`. | | `--access-logs-proxy-request-id-header` | `x-request-id` | Header whose value is logged as `proxy_request_id`. Empty disables it. | Each line ends with `spica_request_id`, `spica_hop_id`, `spica_parent_hop_id`, `proxy_request_id`, `started_at` and `duration_ms`. Every response carries an `x-spica-request-id` header, and requests that a function makes back to Spica share the same request id, so you can follow a request through functions. ## Bucket observability **Observability** in the panel lists every bucket with its document count and health, and opens the query profiler of a bucket to find slow queries. The data comes from `GET /bucket/:bucketId/data/profile`. ![Bucket observability page listing buckets with entity counts and health](https://docs.spicaengine.com/screenshots/panel/observability-bucket.webp) ## Logs of your code Function logs are stored by Spica and can also go to stdout. See [Function logs](https://docs.spicaengine.com/functions/logs). ## A production setup - Point your orchestrator's probes at `/status/live` and `/status/ready`. - Turn on access logs with a status code filter such as `^[45]` and ship stdout to your log platform. - Send function worker logs to stdout with `--function-worker-log-output=database,stdout`. - Propagate your proxy's request id header and search logs by it. - Watch `/status` for growth in documents and storage. --- # Batch requests > Send many API requests in one round trip with the batch endpoint, and control how many run at the same time. The batch endpoint runs several API requests for you and returns all responses together. Use it to save round trips from mobile clients, to import data, or to fan out writes from a function. `POST /batch` ```bash curl -X POST https://api.example.com/api/batch \ -H "Content-Type: application/json" \ -d '{ "concurrency": 2, "requests": [ {"id": "list", "method": "GET", "url": "bucket//data?limit=1", "headers": {"Authorization": "APIKEY "}}, {"id": "create", "method": "POST", "url": "bucket//data", "body": {"title": {"en_US": "Batched"}, "slug": "batched"}, "headers": {"Authorization": "APIKEY "}} ] }' ``` | Field | Description | | -------------------- | ------------------------------------------------------------------------------ | | `requests[].id` | **Required.** Your identifier, echoed in the response. | | `requests[].method` | **Required.** `GET`, `POST`, `PUT`, `PATCH` or `DELETE`. | | `requests[].url` | **Required.** Path relative to the API's public URL, without a leading `/api`. | | `requests[].body` | Optional JSON body. | | `requests[].headers` | Optional headers, including `Authorization`. | | `concurrency` | How many requests run at the same time. `0` (default) means no limit. | ## Response ```json { "responses": [ {"id": "list", "status": 200, "headers": {"content-type": "application/json; charset=utf-8"}, "body": [{"_id": "6b0b1972a5611972c29c25fd", "title": "Hello Spica"}]}, {"id": "create", "status": 201, "headers": {"content-type": "application/json; charset=utf-8"}, "body": {"_id": "6b0b1ba5a5611972c29c2658", "title": {"en_US": "Batched"}, "slug": "batched"}} ] } ``` Each request is authenticated and authorized on its own, with the headers you give it. A failing request doesn't stop the others: check the `status` of each response. ## Tips - Use `concurrency` to protect the database during large imports. - Requests in a batch aren't a transaction. Make them independent, or check each response and compensate on failures. - The [devkit's](https://docs.spicaengine.com/devkit) `insertMany` and `removeMany` use this endpoint. --- # Assets > Package buckets, functions, dashboards and other resources into installable assets, with configurable values, previews and exports. An asset is a package of resources, such as buckets, functions, dashboards, preferences and API keys, that can be installed into a Spica instance as a unit. Assets are useful for reusable features ("contact form", "newsletter"), starter kits and moving a feature between instances. > **Note** > > To keep your whole project in git and deploy it to several environments, prefer [resources as code](https://docs.spicaengine.com/cli/resources-as-code) with `spica plan` and `spica apply`. Use assets for self-contained packages that you install into many projects. ## Anatomy ```json { "name": "Newsletter", "description": "Subscribers bucket and a double opt-in function", "icon": "mail", "url": "https://example.com/assets/newsletter.zip", "resources": [ {"module": "bucket", "contents": {"schema": {"title": "Subscribers", "description": "Newsletter subscribers", "properties": {}}}}, {"module": "function", "contents": {"schema": {}, "index": "export default function () {}", "package": {}}} ], "configs": [ { "title": "Confirmation path", "module": "function", "resource_id": "", "submodule": "schema", "property": "triggers.confirm.options.path", "type": "string", "value": "/newsletter/confirm" } ] } ``` `configs` are the values the installer can change before installing. Each config points at a property of a resource, using dot notation. ## Lifecycle | Endpoint | Action | Purpose | | ------------------------------ | --------------------------- | ------------------------------------------------------------ | | `POST /asset` | | Register an asset. | | `GET /asset`, `GET /asset/:id` | `asset:index`, `asset:show` | List and inspect assets. | | `POST /asset/:id?preview=true` | `asset:install` | See what installing would change, without changing anything. | | `POST /asset/:id` | `asset:install` | Install the asset with the given configs. | | `DELETE /asset/:id` | `asset:delete` | Remove an asset. | | `POST /asset/export` | `asset:export` | Export existing resources as a downloadable asset. | ### Export resources as an asset ```bash curl -X POST https://api.example.com/api/asset/export \ -H "Authorization: IDENTITY " -H "Content-Type: application/json" \ -d '{ "name": "Blog", "description": "Posts and authors", "resources": {"bucket": ["", ""], "function": [""]}, "configs": [] }' -o blog-asset.zip ``` ## Assets with the CLI A folder with an `asset.yaml` and one sub-folder per resource can be uploaded with the CLI: ```text newsletter/ ├── asset.yaml ├── bucket//schema.yaml ├── function//schema.yaml ├── function//index.ts ├── function//package.json └── dashboard//schema.yaml ``` ```bash spica asset apply --path ./newsletter --dry-run spica asset apply --path ./newsletter spica asset delete --path ./newsletter --type soft ``` See [CLI → Assets](https://docs.spicaengine.com/cli/assets). --- # Replication > Run several API replicas behind a load balancer, keep them in sync, and make sure triggered work runs exactly once. A single API replica serves most projects. Run more when you need higher availability or more throughput. Replicas are stateless towards clients, but they share background work such as function triggers, so they must coordinate. ## Turn it on Start every replica with: ```bash --replication=true ``` The [Helm chart](https://docs.spicaengine.com/self-hosting/kubernetes) sets it automatically when `application.replicas` is greater than `1`. With replication on: - Scheduled, bucket and database events are claimed by one replica, so each runs once. - Replicas keep their in-memory state, such as loaded functions and triggers, in step. ## Requirements | Concern | What to do | | ---------------- | ---------------------------------------------------------------------------------------------------------------------------- | | Function sources | Use `--function-asset-storage-strategy=awss3` or `gcs`, or point `--function-asset-path` at a shared volume. | | Uploaded files | Use the `awss3` or `gcloud` storage strategy, or a shared volume (`application.diskAccessMode: ReadWriteMany` in the chart). | | Database | All replicas use the same database. | | Secrets | All replicas use the same master key or secrets. | | Load balancer | Any. WebSocket connections (realtime, firehose) must be allowed. | ## Things that run on every replica - `system` triggers with `READY`, because every replica starts. - In-memory response caches (`--bucket-cache`). Each replica has its own cache and invalidates it on its own writes, so cached reads can be stale for up to `--bucket-cache-ttl` seconds. --- # Admin panel > A tour of Spica's admin panel, the back office where developers configure the backend and content teams manage data. The panel is a web app served next to the API. Developers use it to design buckets, write functions and manage access. Editors and operators use it to manage content, files and users. Everything you can do in the panel is also available through the [API](https://docs.spicaengine.com/buckets/data-api) and the [CLI](https://docs.spicaengine.com/cli). ## Logging in Open the panel's URL, `http://localhost:4500` for a local project, and log in with an [identity](https://docs.spicaengine.com/auth/identities). A new instance has the identity `spica` with the password `spica`. SAML [strategies](https://docs.spicaengine.com/auth/strategies) appear as extra login buttons. ![The panel login page with identifier and password fields and a button to log in with a Spica account](https://docs.spicaengine.com/screenshots/panel/login.webp) ## Layout ![The panel home with the navigation rail on the left, the dashboards sidebar and the resource overview](https://docs.spicaengine.com/screenshots/panel/home.webp) | Area | What you find there | | ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | | Navigation rail (left) | Dashboards, buckets, functions, access management, configuration, webhooks, observability and storage. At the bottom: theme switch and home. | | Sidebar | The items of the selected area, such as buckets or functions, with search and "new" buttons. | | Top bar | Your current token (handy for API calls) and your profile. | | Content | The selected page. | What each person sees depends on their policies. An editor with access to two buckets only sees those buckets. ## Home The home page summarizes the instance: the current release, the number of buckets, documents, functions and users, storage used, usage against configured limits and API traffic over time. ## Tour - [Buckets & entries](https://docs.spicaengine.com/panel/buckets): Design schemas and manage data in tables and forms. - [Functions](https://docs.spicaengine.com/panel/functions): Write code, configure triggers, dependencies and environment, read logs. - [Access management](https://docs.spicaengine.com/panel/access): Identities, users, policies, strategies, API keys and sessions. - [Storage](https://docs.spicaengine.com/panel/storage): Upload, organize and preview files. - [Dashboards](https://docs.spicaengine.com/panel/dashboards): Charts, tables and statistics for your team. - [Webhooks](https://docs.spicaengine.com/panel/webhooks): Outgoing notifications and their delivery logs. - [Secrets & variables](https://docs.spicaengine.com/panel/secrets-and-variables): Configuration and credentials for functions. - [Configuration](https://docs.spicaengine.com/panel/config): Password policies, verification and rate limits. - [Observability](https://docs.spicaengine.com/panel/observability): Bucket health, query profiling and activity. - [Diagram](https://docs.spicaengine.com/panel/diagram): A map of your buckets and their relations. ## Hosting the panel The panel is published as the `spicaengine/panel` image and calls the API at `/api` on its own origin. Serve both behind the same host, with `/` routed to the panel and `/api` to the API. The [CLI](https://docs.spicaengine.com/cli/local-projects) and the [Helm chart](https://docs.spicaengine.com/self-hosting/kubernetes) do this for you. --- # Buckets & entries > Design bucket schemas and manage entries in the panel, with tables, filters, translations, relations and history. ## The data table Open **Buckets** in the navigation rail and pick a bucket from the sidebar. Its entries appear in a table with one column per property. ![The Posts bucket table with id, title, slug, body, status and tags columns, and Filter, Sort, Column and New Entry buttons](https://docs.spicaengine.com/screenshots/panel/bucket.webp) | Control | Use it to | | ------------- | --------------------------------------------------------------- | | **Search** | Find entries by text. | | **Filter** | Build filters on properties, the same filters the API accepts. | | **Sort** | Order by any column. | | **Column** | Show or hide columns. | | **Refresh** | Reload the entries. | | **More** | Bucket actions, such as editing the schema, rules and settings. | | **New Entry** | Open an empty form. | | **New Field** | Add a property to the schema. | Select rows with the checkboxes to delete several entries at once. ## Editing an entry Click an entry's edit icon to open the form. Each property type has its own input: rich text editor, date picker, map, color picker, file picker for `storage` properties and a document picker for relations. ![The Edit Entry drawer with inputs for title, slug, rich text body, status, tags, author relation and cover image](https://docs.spicaengine.com/screenshots/panel/bucket-entry.webp) - **Translations.** Properties with translations get a language switch, so editors can fill in each language. - **Relations.** Pick related entries, or follow the link to open the related entry. - **Files.** Upload a new image or pick one from storage. Images can be edited in place. - **History.** When the bucket keeps history, open earlier versions of the entry and restore them. ## Designing a schema Create a bucket with **New Bucket** in the sidebar, then add properties with **New Field**. For each property you choose a type, a title and the options that type supports: required, default, validation, translations, enum values, relation target and so on. The bucket's menu holds its settings: title, description, icon, category, history, read-only mode, document limits, indexes and [rules](https://docs.spicaengine.com/buckets/rules). > **Tip** > > Keep schemas in git once a project grows: edit them in the panel on a development instance, then `spica fetch` them into your repository and apply them to other instances. See [Resources as code](https://docs.spicaengine.com/cli/resources-as-code). ## Giving editors access Editors only see the buckets their policies allow. Create a policy with the `bucket:data:*` actions of the content buckets, attach it to their identities, and add `StorageFullAccess` if they upload images. See the [content editor policy](https://docs.spicaengine.com/auth/policies#example-content-editor). --- # Functions > Write and deploy functions in the panel's editor, configure triggers, imports, dependencies and environment, and browse logs. ## The editor Open **Functions** in the navigation rail. The sidebar lists your functions; **Add New Function** creates one. ![The function editor with code in the middle and panels for imported functions, triggers, dependencies and environment on the right](https://docs.spicaengine.com/screenshots/panel/function.webp) The code editor gives you syntax highlighting, type information for TypeScript and the devkit, and formatting. The panel on the right configures the function: | Panel | Purpose | | ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | | **Imported Functions** | Import other functions as `@spica-fn/`. See [Sharing code](https://docs.spicaengine.com/functions/dependencies#sharing-code-between-functions). | | **Triggers** | Add, configure, enable or disable triggers. Each trigger points to an exported handler. | | **Dependencies** | Install, update and remove npm packages. | | **Environment** | Attach [environment variables and secrets](https://docs.spicaengine.com/functions/environment). | **Save** builds and deploys the function. The **Logs** drawer at the bottom shows the function's latest logs while you work. ## Logs The function logs page, opened from the functions sidebar header, shows the logs of all functions on a timeline. Filter by level, function, time range or text, and expand entries for details. ![The function logs page with a timeline and a table of log entries](https://docs.spicaengine.com/screenshots/panel/function-logs.webp) ## Variables The **Function variables** page, also opened from the sidebar header, is where you manage the environment variables and secrets available to functions. ![The function variables page listing environment variables](https://docs.spicaengine.com/screenshots/panel/function-variables.webp) ## Working with the CLI Editing in the panel is great for experiments. For team work, keep functions in a repository and use [`spica dev`](https://docs.spicaengine.com/cli/resources-as-code#develop-with-live-sync), which applies your local edits to an instance as you save. --- # Access management > Manage identities, users, policies, login strategies, API keys, refresh tokens, secrets and user activity from the panel. **Access Management** (the people icon in the navigation rail) groups everything about who can do what. ![The Access Management section showing the policies list with built-in full access and read only policies](https://docs.spicaengine.com/screenshots/panel/policy.webp) | Page | What you do there | Read more | | ------------------------- | --------------------------------------------------------------------------------------- | ------------------------------------------------------------------------ | | **Identities** | Create team accounts, set passwords, attach policies, enable two-factor authentication. | [Identities](https://docs.spicaengine.com/auth/identities) | | **Users** | Browse and manage end users, attach policies, ban users. | [Users](https://docs.spicaengine.com/auth/users) | | **Policies** | Inspect built-in policies and write your own with a statement editor. | [Policies](https://docs.spicaengine.com/auth/policies) | | **Strategies** | Add SAML and OAuth login strategies. | [Strategies](https://docs.spicaengine.com/auth/strategies) | | **API Keys** | Create keys, attach policies, deactivate keys. | [API keys](https://docs.spicaengine.com/auth/api-keys) | | **Refresh Tokens** | See active sessions and disable or delete them. | [Tokens & sessions](https://docs.spicaengine.com/auth/tokens) | | **Secrets and Variables** | Manage secrets and environment variables. | [Env vars & secrets](https://docs.spicaengine.com/functions/environment) | | **User Activities** | Follow what end users did. | [Activity stream](https://docs.spicaengine.com/platform/activity) | ![The identities page](https://docs.spicaengine.com/screenshots/panel/identity.webp) ![The API keys page](https://docs.spicaengine.com/screenshots/panel/api-key.webp) ## Good habits - Give every person their own identity. Don't share the default `spica` account. - Prefer custom policies per role to the full access policies. - Review API keys and refresh tokens regularly and remove what isn't used. --- # Storage > Upload, organize, preview and delete files in the panel's storage browser. **Storage** (the tray icon in the navigation rail) is a file browser for the [storage module](https://docs.spicaengine.com/storage). ![The storage browser with an images folder and the files cover.png and hello.txt](https://docs.spicaengine.com/screenshots/panel/storage.webp) | Action | How | | ----------------------- | -------------------------------------------------------------------- | | Upload | **Upload Files**. | | Move | Drag files between folders. | | Create a folder | **Create New Folder**. Folders are objects whose names end with `/`. | | Navigate | Click folders. The sidebar shows where you are. | | Preview | Select a file to preview it. | | Rename, replace, delete | Use the actions of the selected file. | | Find files | **Search**, **Filter** and **Sort**. | Files you upload here can be picked in bucket entries with `storage` properties, and vice versa. > **Note** > > Editors need `StorageFullAccess` (or a custom storage policy) to upload. Exclude folders such as `private/*` in a policy to hide them. --- # Dashboards > Create dashboards in the panel and add charts, tables, statistics and cards backed by your functions. Dashboards live at the top of the navigation rail. The sidebar lists them, and **Add New Dashboard** creates one. ![A dashboard with a line chart of daily views, a statistic tile and a New Component placeholder](https://docs.spicaengine.com/screenshots/panel/dashboard.webp) To add a component, click **New Component** and choose: 1. A **name**. 2. A **type**: `line`, `bar`, `radar`, `pie`, `doughnut`, `polarArea`, `bubble`, `scatter`, `table`, `card` or `statistic`. 3. A **URL** that returns the component's data, usually an [HTTP function](https://docs.spicaengine.com/functions/http). 4. A **size** on the grid. The panel requests the URL with your identity's token, so protect those functions with `authenticate: [IDENTITY]`. The data shape of each type is described in [Dashboards](https://docs.spicaengine.com/platform/dashboards#component-types-and-data). --- # Webhooks > Create, pause and debug webhooks from the panel. **Webhooks** (the hook icon in the navigation rail) lists your [webhooks](https://docs.spicaengine.com/platform/webhooks). **New Webhook** opens a form with the title, target URL, the collection and operation that trigger it, and the body template. ![A webhook detail page with its trigger, running toggle, body template and delivery logs filtered by success or error](https://docs.spicaengine.com/screenshots/panel/webhook.webp) The detail page shows: - The trigger, as `/`, for example `bucket_6b0b.../INSERT`. - A **Running** toggle to pause and resume the webhook. - **Logs** of every delivery, filterable by success and error. Expand a log to see the request and the response. --- # Secrets & variables > Manage the secrets and environment variables that functions use, from the panel. Open **Access Management → Secrets and Variables**. The page has two tabs: | Tab | Contents | | ------------- | --------------------------------------------------------------------------------- | | **Secrets** | Encrypted credentials. Values can be set and replaced, but never displayed again. | | **Variables** | Plain configuration values. | ![The secrets and variables page with a secrets tab and a variables tab](https://docs.spicaengine.com/screenshots/panel/secrets-and-variables.webp) Attach them to functions in the **Environment** box of the function editor. See [Env vars & secrets](https://docs.spicaengine.com/functions/environment). --- # Configuration > Change password policies, verification channels, passwordless login and rate limits for users and identities from the panel. **Configuration** (the gear icon in the navigation rail) edits the [config module](https://docs.spicaengine.com/platform/config) with forms generated from its schemas. ![The configuration page with User and Identity cards](https://docs.spicaengine.com/screenshots/panel/config.webp) | Module | Settings | | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | **User** | Password policy, email and phone verification, password reset, passwordless login, verification attempts and rate limits. | | **Identity** | Password policy for your team. | | **Data Strategy** | Per bucket, choose whether the panel loads entries over HTTP on demand or streams them live over [realtime](https://docs.spicaengine.com/buckets/realtime), and which property labels related entries. Stored in your browser. | A module shows "Not configured yet" until it has been saved once. Saving replaces the module's previous settings. --- # Observability & activity > Check bucket health, profile slow queries and follow what happened in your instance from the panel. ## Bucket observability **Observability** (the shield icon in the navigation rail) lists every bucket with its number of entries and its health. Open a bucket's **Profiler** to see the slowest recent queries, with their filters and durations, and decide which [indexes](https://docs.spicaengine.com/buckets/advanced#indexes) to add. ![The bucket observability page with Authors, Posts, Customers and Tags, their entity counts and a Healthy status](https://docs.spicaengine.com/screenshots/panel/observability-bucket.webp) ## Activities The activities page shows the [activity stream](https://docs.spicaengine.com/platform/activity): who inserted, changed or deleted what, and when. Filter by identity, action, resource and date. ![The activities page listing actions with identifier, action, resource and date](https://docs.spicaengine.com/screenshots/panel/activity.webp) ## Instance overview The panel home shows usage per module, usage against limits and API traffic. See [Status & observability](https://docs.spicaengine.com/platform/observability). --- # Diagram > See your buckets and the relations between them as an interactive diagram. The diagram page draws every bucket as a node and every relation property as an edge between two buckets. Use it to understand an existing data model at a glance, especially in projects with many buckets. - Zoom and pan with the controls in the corner, or with your mouse or trackpad. - Drag nodes to arrange the layout. - The minimap shows where you are in large models. Relations appear in the diagram as soon as you add a `relation` property to a bucket. See [Relations](https://docs.spicaengine.com/buckets/schema#relations). --- # Spica CLI > Install @spica/cli to run Spica locally with Docker, manage resources as code, and automate deployments from CI. `@spica/cli` is the command-line tool for working with Spica. It does three jobs: | Job | Commands | | ---------------------------------------------------------------- | ---------------------------------------------------------------------- | | Run Spica on your machine | `spica project start`, `ls`, `upgrade`, `remove` | | Keep buckets, functions, policies, env vars and secrets in files | `spica fetch`, `plan`, `apply`, `dev`, `env`, `secret`, `guard` | | Connect to instances and generate code | `spica context`, `bucket orm`, `function orm`, `asset`, `project sync` | ## Install ```bash npm install -g @spica/cli spica --version ``` Requirements: - Node.js 20 or newer. - Docker, for `spica project` commands. Use the CLI version that matches your Spica instances, for example `npm install -g @spica/cli@0.22.1`. ## Getting help ```bash spica --help spica help project start ``` Global options: | Option | Effect | | --------------- | --------------------------------- | | `-h, --help` | Show help. | | `-V, --version` | Show the version. | | `-v, --verbose` | Also print debug messages. | | `--quiet` | Only print warnings and errors. | | `--silent` | Print nothing. Use the exit code. | | `--no-color` | Disable colors. | ## A typical workflow ```bash # 1. Run a local instance spica project start dev # 2. Point the CLI at it spica context set --name local --url http://localhost:4500/api --apikey spica context switch local # 3. Export its resources into your repository spica fetch # 4. Edit files with live sync spica dev # 5. Review and deploy to another instance spica context switch production spica plan spica apply ``` ## Next steps - [Contexts](https://docs.spicaengine.com/cli/contexts): Connect the CLI to your instances. - [Local projects](https://docs.spicaengine.com/cli/local-projects): Run Spica with Docker on your machine. - [Resources as code](https://docs.spicaengine.com/cli/resources-as-code): Fetch, plan, apply and live-sync your project. - [Command reference](https://docs.spicaengine.com/cli/reference): Every command and option. --- # Contexts > Save the URL and API key of each Spica instance as a named context, and switch between local, staging and production. A context is a named connection: the API URL of an instance and the API key the CLI uses for it. Every command that talks to an instance (`fetch`, `plan`, `apply`, `dev`, `bucket orm`, `function orm`, `asset`) uses the **current** context. ## Create a key for the CLI In the panel, open **Access Management → API Keys**, create a key, and attach the full-access policies of the modules you manage with the CLI: `BucketFullAccess`, `FunctionFullAccess`, `PolicyFullAccess`, `EnvVarFullAccess` and `SecretFullAccess`. ## Add and select a context ```bash spica context set --name local --url http://localhost:4500/api --apikey spica context switch local ``` ```text Context has been changed to "local". ``` `context set` creates or updates a context. It doesn't select it, so run `context switch` afterwards. | Option | Description | | -------------- | --------------------------------------------------------------------------------------------- | | `--name` | Name of the context. | | `--url` | **Required.** Public URL of the API, including `/api` when the API is served under that path. | | `-a, --apikey` | **Required.** The API key. | ## List and remove contexts ```bash spica context ls ``` ```text NAME URL AUTHORIZATION local http://localhost:4500/api * * * * * * * * * * production https://api.example.com/api * * * * * * * * * * ``` ```bash spica context remove production ``` ## Where contexts are stored Contexts are saved in `~/.spicactx` as JSON, with the key in plain text: ```json {"local": {"url": "http://localhost:4500/api", "authorization": "APIKEY 4yVYTsoIdIBETPoFn2jXoDY72i46L5I6"}} ``` Keep that file private. In CI, create the context from secrets at the start of the job: ```bash spica context set --name ci --url "$SPICA_URL" --apikey "$SPICA_API_KEY" spica context switch ci ``` ## Guarding production To avoid running `plan` or `apply` from the wrong folder, restrict them with a [guard](https://docs.spicaengine.com/cli/resources-as-code#guards). --- # Local projects > Run complete Spica projects on your machine with Docker, on MongoDB or PostgreSQL, and upgrade or remove them. `spica project` runs a complete Spica instance in Docker: the API, the panel, a database and an nginx ingress that serves both on one port. ## Start a project ```bash spica project start my-app ``` ```text ✔ Pulling images (4/4) ✔ Creating a network named my-app-network. ✔ Creating database containers (1/1) ✔ Waiting for the replica set to become ready. ✔ Creating spica containers (2/2) ✔ Creating an ingress to route traffic. Spica my-app is serving on http://localhost:4500. Open your browser on http://localhost:4500/dashboard to login. Identitifer: spica Password: spica ``` | Option | Default | Description | | ------------------------- | ---------------- | ------------------------------------------------------------------------------------------------------ | | `--image-version` | `latest` | Spica version to run, for example `0.22.1`. | | `-p, --port` | `4500` | Port of the ingress. A free port is picked when it is taken. | | `--database-type` | `mongodb` | `mongodb` or `postgresql`. | | `--database-replicas` | `1` | MongoDB replica set members. PostgreSQL runs one node. | | `--mongo-version` | `8.0` | MongoDB image tag. | | `--postgres-version` | `18` | PostgreSQL image tag. | | `--api-options` | | Path to a JSON file with extra [API options](https://docs.spicaengine.com/self-hosting/configuration). | | `-o, --open` | | Open the panel when ready. | | `-f, --force` | | Replace a project with the same name. | | `--retain-volumes` | `true` | With `--force`, keep the existing data. | | `--restart` | `true` | Restart containers that exit unexpectedly. | | `--image-pull-policy` | `if-not-present` | `default` pulls images every time. | | `--local-resource-folder` | | Mount a folder that the API keeps in two-way sync with its resources. | ### What runs | Container | Image | Role | | ---------------- | --------------------------------- | ----------------------------------------------------------------- | | `-ingress` | `nginx` | Serves the panel at `/` and the API at `/api` on the chosen port. | | `-spica` | `spicaengine/panel` | Admin panel. | | `-api` | `spicaengine/api` | API. | | `-db-0` | `mongo` or `spicaengine/postgres` | Database. Data is kept in a Docker volume. | The API is started with `--public-url=http://localhost:/api`, a master key equal to the project name and `--persistent-path=/var/data`. ### Extra API options Put options in a JSON file, keyed by option name without dashes: ```json title="api-options.json" { "bucket-graphql": true, "function-timeout": 120, "passport-default-identity-password": "a-better-password" } ``` ```bash spica project start my-app --api-options $(pwd)/api-options.json ``` Options that the CLI sets itself (database, public URL, master key and persistent path) can't be overridden this way. ## List projects ```bash spica project ls ``` Shows each project's namespace, status, version and port. ## Upgrade ```bash spica project upgrade my-app 0.22.1 ``` Replaces the API and panel containers with the given version and keeps your data. ## Remove ```bash spica project remove my-app ``` Stops and removes the containers and network. Data volumes are kept unless you pass `--retain-volumes=false`. > **Note** > > Local projects are meant for development. Their master key is the project name and the default identity keeps the password `spica`. Use [Docker](https://docs.spicaengine.com/self-hosting/docker) or [Kubernetes](https://docs.spicaengine.com/self-hosting/kubernetes) setups for anything shared. --- # Resources as code > Keep buckets, functions, policies, environment variables and secrets in a git repository, and fetch, plan, apply and live-sync them with the CLI. Resources as code lets you treat a Spica instance like infrastructure: the source of truth is a folder of YAML and code files in git, changes are reviewed in pull requests, and `spica apply` brings an instance in line with the files. _Diagram: spica fetch copies resources from an instance into the project folder. spica plan and spica apply compare the folder with the instance and apply the differences. spica dev watches the folder and applies changes as you save._ ## Project layout ```text my-project/ ├── bucket/ │ ├── Posts/schema.yaml │ └── Authors/schema.yaml ├── function/ │ └── hello/ │ ├── schema.yaml │ ├── index.mjs # or index.ts for TypeScript functions │ └── package.json ├── policy/ │ └── Blog Reader/schema.yaml ├── env-var/ │ └── SITE_URL/schema.yaml ├── secret/ │ └── STRIPE_KEY/schema.yaml └── .spica/ # per-context values, keep out of git └── local.env ``` | Module | Folder name | Files | | ---------- | ------------- | -------------------------------------------------------- | | `bucket` | Bucket title | `schema.yaml` | | `function` | Function name | `schema.yaml`, `index.mjs` or `index.ts`, `package.json` | | `policy` | Policy name | `schema.yaml` | | `env-var` | Key | `schema.yaml` | | `secret` | Key | `schema.yaml` (never contains the value) | Resources are matched by folder name, and by `_id` when the file has one. Files written by `spica fetch` include `_id`. ```yaml title="bucket/Tags/schema.yaml" title: Tags description: Tags used to group posts primary: name properties: name: type: string title: Name color: type: color title: Color ``` Add `.spica/` to your `.gitignore`. ## Fetch Export an instance's resources into the current folder (or `[dir]`): ```bash spica fetch ``` ```text ── ENVIRONMENT VARIABLE ── +1 + GREETING key: GREETING ── FUNCTION ── +1 + hello 2 triggers Plan: +7 to write ~0 to update -0 to delete ✓ Fetch complete. +7 written ``` | Option | Description | | -------------------- | -------------------------------------------------------------- | | `-y, --auto-approve` | Write without asking. | | `--clean` | Delete local folders whose resources no longer exist remotely. | | `--module ` | Only `policy`, `bucket`, `env-var`, `secret` or `function`. | | `--detailed` | Show full diffs before writing. | | `--concurrency ` | Parallel requests and writes (default 10). | | `--abort-on-error` | Stop at the first failure. | ## Plan Compare the folder with the current context's instance and show what `apply` would do: ```bash spica plan --detailed ``` ```text ── BUCKET ── +1 ~1 + Tags 2 properties ~ Posts 11 properties [description] --- remote/schema.yaml +++ local/schema.yaml -description: Blog posts +description: Articles published on the blog ── ENVIRONMENT VARIABLE ── +1 + SITE_URL key: SITE_URL Plan: +2 to create ~1 to update -0 to delete ``` | Option | Description | | --------------------- | ---------------------------------------------------------------------------------------- | | `--detailed` | Show unified diffs instead of field names. | | `--json` | Print the plan as JSON for scripts. | | `--detailed-exitcode` | Exit with `0` when there are no changes, `1` on errors and `2` when changes are planned. | | `--module ` | Limit to one module. | | `--concurrency ` | Parallel requests (default 10). | The JSON plan lists creates, updates and deletes per module: ```json [{"module": "bucket", "creates": [], "updates": [{"slug": "Tags", "summary": "2 properties", "changedFields": ["history", "acl", "indexes", "icon"]}], "deletes": []}] ``` > **Danger: Deleting a folder deletes the resource** > > The folder is the desired state. A bucket, function or policy that exists on the instance but not in the folder appears as `-` in the plan and is **deleted** by `apply`, including all documents of a bucket. Always read the plan, and use `--module` when you only manage part of a project. ## Apply ```bash spica apply ``` `apply` shows the plan, asks for confirmation and applies it: ```text Applying changes… ✔ Updating Bucket: Posts (1/1) ✔ Creating Bucket: Tags (1/1) ✔ Creating Environment Variable: SITE_URL (1/1) ✓ Apply completed. +2 created ~1 updated -0 deleted ``` | Option | Description | | -------------------- | -------------------------------- | | `-y, --auto-approve` | Apply without asking. Use in CI. | | `--module ` | Limit to one module. | | `--detailed` | Show full diffs before applying. | | `--concurrency ` | Parallel requests (default 5). | | `--abort-on-error` | Stop at the first failure. | After you create new resources, run `spica fetch` once. The server fills in defaults (such as `acl`, `icon` and `indexes`) and ids, and fetching them keeps the next plan clean. ## Develop with live sync `spica dev` checks that the folder and the instance are in sync, then watches your files and applies every change as you save: ```bash spica dev ``` ```text ✓ Already in sync. Starting watcher… 👁 Watching for changes in /home/me/my-project… (Ctrl-C to stop) ✔ ~ Function hello [index] updated ``` It watches `schema.yaml`, `index.ts`, `index.mjs`, `index.js` and `package.json`, and only uploads what changed: a code change uploads the code, a `package.json` change installs dependencies. Use it against a local or personal development instance, never against production. ## Values per environment Environment variable values can differ between instances, and secret values must never be committed. The CLI resolves them per context. See [Values per environment](https://docs.spicaengine.com/cli/values). ## Guards A guard pins `plan` and `apply` to one directory on your machine, and optionally requires some folders to exist, so that you can't apply the wrong folder by accident: ```bash spica guard set --path ~/work/my-project --folders bucket,function,policy,env-var,secret spica guard show spica guard remove ``` The guard is stored in `~/.spicaguard`. While it is set, `plan` and `apply` fail outside that directory: ```text Invalid working directory: "/tmp/other". This command must be run from "/home/me/work/my-project". ``` ## Recommended workflow 1. Develop against a local instance with `spica project start` and `spica dev`. 2. Commit the files. Never commit `.spica/`. 3. In CI, run `spica plan --detailed-exitcode` on pull requests and post the plan for review. 4. After merge, run `spica apply -y` against staging, then production. See the [CI/CD with GitHub Actions](https://docs.spicaengine.com/recipes/ci-cd-github-actions) recipe, and [`@spica-devkit/sync`](https://docs.spicaengine.com/devkit/sync) to plan and apply from your own services. --- # Values per environment > Keep environment variable and secret values out of git, set them per CLI context, and provide them from CI with SPICA_VALUE\_ variables. Environment variables and secrets are declared in the project (`env-var//schema.yaml`, `secret//schema.yaml`), but their values usually differ between instances, and secret values must never be committed. The CLI resolves values for the current [context](https://docs.spicaengine.com/cli/contexts). ## Declare a key ```yaml title="env-var/SITE_URL/schema.yaml" key: SITE_URL ``` ```yaml title="secret/STRIPE_KEY/schema.yaml" key: STRIPE_KEY ``` An environment variable's `schema.yaml` may also contain a `value`, which then acts as the default for every context. ## Set values for the current context ```bash spica env SITE_URL https://blog.example.com spica secret STRIPE_KEY ``` ```text Saved SITE_URL to .spica/local.env. ``` `spica secret` prompts for the value without echoing it. Both commands write to `.spica/.env` (file mode `600`) in the project folder: ```dotenv title=".spica/local.env" SITE_URL=https://blog.example.com STRIPE_KEY='sk_test_...' ``` A key must be declared before you can set it, otherwise the CLI answers `"SITE_URL" is not declared. Create env-var/SITE_URL/schema.yaml first.` ## How values are resolved For each key, `plan`, `apply` and `dev` use the first value they find: 1. The `SPICA_VALUE_` environment variable, for example `SPICA_VALUE_STRIPE_KEY`. 2. `.spica/.env`. 3. The `value` in the environment variable's `schema.yaml`. When an environment variable has no value anywhere, or a secret doesn't exist on the instance yet and has no value, the plan stops: ```text Missing values for: env-var/SITE_URL Set them with "spica env " / "spica secret " or the SPICA_VALUE_ environment variable. ``` A secret that already exists on the instance doesn't need a value. Its current value is kept. ## In CI Provide values as environment variables from your CI's secret store: ```yaml env: SPICA_VALUE_STRIPE_KEY: ${{ secrets.STRIPE_KEY }} SPICA_VALUE_SITE_URL: https://blog.example.com ``` > **Note** > > `spica fetch` writes environment variable values into `schema.yaml`. If a value differs per environment, remove it from the file after fetching and set it with `spica env` or `SPICA_VALUE_` variables instead. --- # Assets > Upload a folder of resources as an asset with spica asset apply, preview it with --dry-run, and remove it with spica asset delete. `spica asset` uploads a folder of resources as an [asset](https://docs.spicaengine.com/platform/assets) to the current context's instance. ## Folder layout ```text newsletter/ ├── asset.yaml ├── bucket//schema.yaml ├── function//schema.yaml ├── function//index.ts # or index.js ├── function//package.json ├── function//env.env ├── dashboard//schema.yaml ├── preference//schema.yaml └── apikey//schema.yaml ``` Resource folders are named by id (an ObjectId or a UUID). `asset.yaml` holds the asset's metadata: ```yaml title="asset.yaml" name: Newsletter description: Subscribers bucket and a double opt-in function icon: mail configs: [] ``` ## Commands ```bash spica asset apply --path ./newsletter --dry-run spica asset apply --path ./newsletter spica asset delete --path ./newsletter --type soft ``` | Command | Options | | -------------------- | --------------------------------------------------------------------------------------- | | `spica asset apply` | `--path` (default: current directory), `--dry-run` to only list what would be uploaded. | | `spica asset delete` | `--path`, `--type soft` or `hard` (required). | > **Tip** > > To manage a whole project across environments, use [resources as code](https://docs.spicaengine.com/cli/resources-as-code) instead. Assets are meant for packages you install into many instances. --- # Project sync > Copy buckets, bucket data, functions, API keys, policies and environment variables directly from one Spica instance to another. `spica project sync` copies resources from a source instance to a target instance, without files in between. It's handy for one-off migrations, such as cloning production data into a staging instance. > **Danger** > > Sync adds, overwrites **and removes** objects on the target, and it can't be undone. Run it with `--dry-run` first, and prefer [resources as code](https://docs.spicaengine.com/cli/resources-as-code) for repeatable deployments. ```bash spica project sync \ --source-url https://api.prod.example.com/api --source-apikey "$PROD_KEY" \ --target-url https://api.staging.example.com/api --target-apikey "$STAGING_KEY" \ --modules bucket,bucket-data,function \ --dry-run ``` | Option | Description | | --------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | | `--source-url`, `--source-apikey` | **Required.** The instance to copy from. | | `--target-url`, `--target-apikey` | **Required.** The instance to copy to. | | `--modules` | **Required.** Comma-separated: `bucket`, `bucket-data`, `function`, `apikey`, `policy`, `env-var`. | | `--bucket-ids`, `--function-ids`, `--apikey-ids`, `--policy-ids`, `--env-var-ids` | Limit a module to some ids, comma-separated. | | `--dry-run` | Show the changes without applying them. | | `--concurrency-limit` | Parallel requests to the target (default 100). Lower it if you see `ECONNRESET`. | | `--ignore-errors` | Continue when a request fails. | Both instances should run the same Spica version. --- # Code generation > Generate a typed client for your buckets and typed callers for your HTTP functions from a live instance. The CLI reads the buckets and functions of the current [context](https://docs.spicaengine.com/cli/contexts) and generates TypeScript you can use in apps and functions. ## Bucket ORM ```bash spica bucket orm --path ./src/spica ``` ```text ✔ Succesfully completed! File url is /home/me/app/src/spica/bucket.ts ``` `bucket.ts` contains an interface per bucket and a typed cursor per bucket, built on [`@spica-devkit/bucket`](https://docs.spicaengine.com/devkit/bucket): ```typescript title="Generated (excerpt)" export interface Posts { _id?: string; title: Localize extends true ? string : {"tr_TR": "string", "en_US": "string"}; slug: string; status?: ("draft" | "published"); tags?: string[]; author?: Find[] extends never[] ? string : (Authors[]> & id); views?: number; published_at?: Date | string; } export const posts = new PostsCursor("6b0b1968a5611972c29c25f7", Bucket.data, PostsRelationFields); ``` Use it with chained query options: ```typescript import {initialize, posts} from "./spica/bucket"; initialize({apikey: process.env.SPICA_API_KEY}); const latest = await posts .filter('document.status == "published"') .sort({published_at: -1}) .limit(10) .resolveRelations(["author"]) .getAll(); latest[0].author.name; // typed, because the author relation was resolved await posts.insert({title: {en_US: "Typed!"}, slug: "typed"}); ``` | Cursor method | Effect | | ----------------------------------------------------------- | -------------------------------------- | | `filter(expression)`, `sort(object)`, `limit(n)`, `skip(n)` | Query options. | | `paginate()` | Return `{meta, data}`. | | `translate(language)` | Request a language. | | `nonLocalize()` | Return every language. | | `resolveRelations(paths)` | Resolve relations, with typed results. | | `get(id)`, `getAll()` | Read. | | `insert(doc)`, `update(doc)`, `patch(doc)`, `remove(id)` | Write. | `initialize` is pre-configured with the context's URL. Install `@spica-devkit/bucket` in the project that uses the file, and regenerate it whenever schemas change. ## Function ORM ```bash spica function orm --path ./src/functions --trigger-types http ``` For every function with an HTTP trigger, the CLI writes `/index.js` and `index.d.ts` with a caller per handler, using `axios`: ```javascript title="Generated hello/index.js (excerpt)" import axios from "axios"; export default function (config) { config = {...config, method: "get", url: "http://localhost:4500/api/fn-execute/hello"}; return axios.request(config).then(r => r.data); } ``` ```typescript import hello from "./src/functions/hello"; const result = await hello({params: {name: "Ada"}}); ``` | Option | Default | Description | | ----------------- | ----------------- | ---------------------------------------- | | `--path` | Current directory | Output folder. | | `--trigger-types` | `http` | Trigger types to generate callers for. | | `--http-service` | `axios` | HTTP library used by the generated code. | --- # Command reference > Every Spica CLI command with its arguments and options. Run `spica help ` for the same information in your terminal. ## Projects ### `spica project start ` Start a local project with Docker. See [Local projects](https://docs.spicaengine.com/cli/local-projects). | Option | Default | | ------------------------------- | ---------------------------------------------- | | `--image-version` | `latest` | | `-p, --port` | `4500` | | `--database-type` | `mongodb` (`mongodb`, `postgresql`) | | `--database-replicas` | `1` | | `--mongo-version` | `8.0` | | `--postgres-version` | `18` | | `--api-options ` | | | `--local-resource-folder ` | | | `--image-pull-policy` | `if-not-present` (`if-not-present`, `default`) | | `-o, --open` | | | `-f, --force` | | | `--retain-volumes` | `true` | | `--restart` | `true` | ### `spica project ls` List local projects. ### `spica project upgrade ` Upgrade a local project to version ``. Option: `--restart` (default `true`). ### `spica project remove ` Remove a local project. Option: `--retain-volumes` (default `true`). ### `spica project sync` Copy resources between two instances. See [Project sync](https://docs.spicaengine.com/cli/project-sync). | Option | | | --------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | | `--source-url`, `--source-apikey` | Required | | `--target-url`, `--target-apikey` | Required | | `--modules` | Required: `bucket`, `function`, `bucket-data`, `apikey`, `policy`, `env-var` | | `--bucket-ids`, `--function-ids`, `--apikey-ids`, `--policy-ids`, `--env-var-ids` | | | `--dry-run` | | | `--concurrency-limit` | Default `100` | | `--ignore-errors` | | ## Contexts | Command | Description | | ------------------------------------------------------------ | --------------------------- | | `spica context set --name --url --apikey ` | Create or update a context. | | `spica context switch ` | Select a context. | | `spica context ls` | List contexts. | | `spica context remove ` | Remove a context. | ## Resources as code All commands take an optional `[dir]`, the project directory (default: the current directory). See [Resources as code](https://docs.spicaengine.com/cli/resources-as-code). ### `spica fetch [dir]` | Option | Default | | -------------------- | ------- | | `-y, --auto-approve` | `false` | | `--clean` | `false` | | `--module ` | All | | `--detailed` | `false` | | `--concurrency ` | `10` | | `--abort-on-error` | `false` | ### `spica plan [dir]` | Option | Default | | --------------------- | ------- | | `--detailed` | `false` | | `--detailed-exitcode` | `false` | | `--json` | `false` | | `--module ` | All | | `--concurrency ` | `10` | ### `spica apply [dir]` | Option | Default | | -------------------- | ------- | | `-y, --auto-approve` | `false` | | `--detailed` | `false` | | `--module ` | All | | `--concurrency ` | `5` | | `--abort-on-error` | `false` | ### `spica dev [dir]` | Option | Default | | ------------------- | ------- | | `--module ` | All | | `--concurrency ` | `10` | `--module` accepts `policy`, `bucket`, `env-var`, `secret` or `function`. ### `spica env ` Set an environment variable's value for the current context. See [Values per environment](https://docs.spicaengine.com/cli/values). ### `spica secret ` Set a secret's value for the current context. Prompts for the value. ### `spica guard set --path [--folders ]` Restrict `plan` and `apply` to a directory, and optionally require folders such as `bucket,function,policy`. ### `spica guard show`, `spica guard remove` Show or remove the guard. ## Code generation ### `spica bucket orm` | Option | Default | | -------------- | ----------------- | | `--path ` | Current directory | ### `spica function orm` | Option | Default | | ------------------------- | ----------------- | | `--path ` | Current directory | | `--trigger-types ` | `http` | | `--http-service ` | `axios` | ## Assets | Command | Options | | -------------------- | ---------------------------------------------- | | `spica asset apply` | `--path `, `--dry-run` | | `spica asset delete` | `--path `, `--type soft\|hard` (required) | ## Global options | Option | Effect | | --------------- | ------------------------------- | | `-h, --help` | Show help. | | `-V, --version` | Show the version. | | `-v, --verbose` | Print debug messages. | | `--quiet` | Only print warnings and errors. | | `--silent` | Print nothing. | | `--no-color` | Disable colors. | --- # Devkit > Typed JavaScript packages for calling Spica from functions, browsers, Node.js services, CI and tests. The devkit is a set of npm packages that wrap Spica's APIs with typed functions. They work in Spica functions, browsers and Node.js. | Package | Use it to | | ------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | | [`@spica-devkit/bucket`](https://docs.spicaengine.com/devkit/bucket) | Manage buckets and read, write and stream bucket data. | | [`@spica-devkit/auth`](https://docs.spicaengine.com/devkit/auth) | Sign users up and in, verify emails and phones, reset passwords, passwordless login. | | [`@spica-devkit/identity`](https://docs.spicaengine.com/devkit/identity) | Log identities in, manage identities and two-factor authentication. | | [`@spica-devkit/storage`](https://docs.spicaengine.com/devkit/storage) | Upload, download and manage files. | | [`@spica-devkit/database`](https://docs.spicaengine.com/devkit/database) | Access MongoDB directly from functions. | | [`@spica-devkit/sync`](https://docs.spicaengine.com/devkit/sync) | Plan and apply resource files from your own services. | | [`@spica-devkit/testing`](https://docs.spicaengine.com/devkit/testing) | Start disposable Spica instances for end-to-end tests. | ```bash npm install @spica-devkit/bucket @spica-devkit/auth @spica-devkit/storage ``` Use the same version as your Spica instance. ## Initialize Every package except `database`, `sync` and `testing` has an `initialize` function. Call it once with credentials and the API's public URL: ```typescript import * as Bucket from "@spica-devkit/bucket"; Bucket.initialize({apikey: "", publicUrl: "https://api.example.com/api"}); Bucket.initialize({identity: "", publicUrl: "https://api.example.com/api"}); Bucket.initialize({user: "", publicUrl: "https://api.example.com/api"}); ``` | Credential | Sent as | Use it | | ---------- | ---------------- | --------------------------------------- | | `apikey` | `APIKEY ` | On servers and in functions. | | `identity` | `IDENTITY ` | In internal tools used by your team. | | `user` | `USER ` | In your product's clients. Rules apply. | `@spica-devkit/auth` can also be initialized with only `publicUrl`, for calls such as `signIn` that don't need credentials. ### Inside functions Functions know where the API is, so `publicUrl` can be left out. Initialize once at module level: ```javascript import * as Bucket from "@spica-devkit/bucket"; Bucket.initialize({apikey: process.env.SPICA_API_KEY}); export default async function () { return Bucket.data.getAll(process.env.POSTS_BUCKET_ID, {queryParams: {limit: 5}}); } ``` Install the devkit as a [function dependency](https://docs.spicaengine.com/functions/dependencies) and keep the API key in a [secret](https://docs.spicaengine.com/functions/environment). ## Per-call headers Most functions accept a last `headers` argument, for example to send `Accept-Language` or to call with another user's token: ```typescript await Bucket.data.get(bucketId, documentId, {headers: {"Accept-Language": "tr_TR"}}); ``` ## Errors Failed requests reject with the API's error, for example: ```json {"statusCode": 403, "message": "You do not have sufficient permissions to do bucket:data:index on resource 6b0b1968a5611972c29c25f7", "error": "Forbidden"} ``` ## Engines The devkit types use `_id`, as MongoDB instances do. On PostgreSQL instances, documents and resources are identified by `id` and by the bucket's primary property, so read those fields instead. See [MongoDB and PostgreSQL](https://docs.spicaengine.com/self-hosting/databases). --- # @spica-devkit/bucket > Manage bucket schemas and read, write and stream bucket data with a typed client. ```bash npm install @spica-devkit/bucket ``` ```typescript import * as Bucket from "@spica-devkit/bucket"; Bucket.initialize({apikey: process.env.SPICA_API_KEY, publicUrl: "https://api.example.com/api"}); ``` ## Data | Function | Description | | ------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | | `data.get(bucketId, documentId, {queryParams?, headers?})` | Get one document. | | `data.getAll(bucketId, {queryParams?, headers?})` | List documents. With `paginate: true`, returns `{meta, data}`. | | `data.insert(bucketId, document, headers?)` | Insert a document. | | `data.insertMany(bucketId, documents, headers?)` | Insert several documents with one [batch request](https://docs.spicaengine.com/platform/batch). | | `data.update(bucketId, documentId, document, headers?)` | Replace a document. | | `data.patch(bucketId, documentId, changes, headers?)` | Patch a document. | | `data.remove(bucketId, documentId, headers?)` | Delete a document. | | `data.removeMany(bucketId, documentIds, headers?)` | Delete several documents with one batch request. | `queryParams` accepts the [query parameters](https://docs.spicaengine.com/buckets/querying) of the data API: `filter`, `sort`, `limit`, `skip`, `paginate`, `relation` and `localize`. ```typescript interface Post { _id?: string; title: string; status: "draft" | "published"; views: number; } const {meta, data} = await Bucket.data.getAll(POSTS, { queryParams: { filter: 'document.status == "published"', sort: {views: -1}, limit: 10, paginate: true, relation: ["author"] }, headers: {"Accept-Language": "en_US"} }); const created = await Bucket.data.insert(POSTS, {title: "Hello", status: "draft", views: 0}); await Bucket.data.patch(POSTS, created._id, {status: "published"}); ``` ## Realtime `data.realtime.getAll` and `data.realtime.get` open a [realtime](https://docs.spicaengine.com/buckets/realtime) connection and return an RxJS observable of the current result, plus methods to write through the connection. ```typescript const posts = Bucket.data.realtime.getAll(POSTS, { filter: 'document.status == "published"', sort: {created_at: -1}, limit: 20 }); const subscription = posts.subscribe(list => render(list)); posts.insert({title: "Live", status: "published", views: 0}); posts.patch({_id: "6b0b...", views: 10}); posts.replace({_id: "6b0b...", title: "Replaced", status: "draft", views: 0}); posts.remove({_id: "6b0b..."}); subscription.unsubscribe(); ``` ```typescript const post = Bucket.data.realtime.get(POSTS, postId); post.subscribe(current => render(current)); post.patch({views: 11}); ``` | Function | Returns | | ------------------------------------------------------------------------- | ----------------------------------------------------------------------------- | | `data.realtime.getAll(bucketId, queryParams?, messageCallback?)` | Observable of the document list, with `insert`, `replace`, `patch`, `remove`. | | `data.realtime.get(bucketId, documentId, messageCallback?, queryParams?)` | Observable of one document, with `replace`, `patch`, `remove`. | `messageCallback` receives the server's response to each write, for example `{status: 204, message: "No Content"}`. Connections reconnect automatically when they drop. ## Schemas | Function | Description | | -------------------------- | ----------------------------- | | `get(bucketId)` | Get a bucket definition. | | `getAll()` | List buckets. | | `insert(bucket)` | Create a bucket. | | `insertMany(buckets)` | Create several buckets. | | `update(bucketId, bucket)` | Replace a bucket definition. | | `remove(bucketId)` | Delete a bucket and its data. | | `removeMany(bucketIds)` | Delete several buckets. | ## Typed clients Generate interfaces and query cursors for all your buckets with [`spica bucket orm`](https://docs.spicaengine.com/cli/orm). --- # @spica-devkit/auth > Sign users up and in, manage sessions, verify emails and phone numbers, reset passwords and log users in without passwords. `@spica-devkit/auth` works with [users](https://docs.spicaengine.com/auth/users), your product's end users. ```bash npm install @spica-devkit/auth ``` ```typescript import * as Auth from "@spica-devkit/auth"; // In a client: no credentials needed to sign in Auth.initialize({publicUrl: "https://api.example.com/api"}); // On a server or in a function: an API key for administrative calls Auth.initialize({apikey: process.env.SPICA_API_KEY}); ``` ## Sign up and sign in ```typescript const user = await Auth.signUp({username: "ada@example.com", password: "aStrongPassword1"}); const session = await Auth.signIn("ada@example.com", "aStrongPassword1"); session.token; // the user JWT session.userId; session.username; const me = await session.get(); await session.updatePassword("anEvenStrongerPassword2"); const freshToken = await session.refreshAccessToken(); ``` `signUp` calls `POST /passport/user`, which needs an API key or an identity with `passport:user:create`. Run it on your server or in a [function](https://docs.spicaengine.com/recipes/user-signup-verification), not in the browser. | Function | Description | | ------------------------------------------------------ | ------------------------------------------------------------------- | | `signUp({username, password}, headers?)` | Create a user. | | `signIn(username, password, tokenLifeSpan?, headers?)` | Log in. Returns a `UserSession`. | | `verifyToken(token, headers?)` | Verify a user token and return its payload. | | `refreshAccessToken(accessToken, headers?)` | Exchange an expired token for a new one (needs the refresh cookie). | ## Verification, reset and passwordless login These flows need the matching settings in the `user` [configuration](https://docs.spicaengine.com/platform/config), and a configured [mailer or SMS sender](https://docs.spicaengine.com/platform/mailer-and-sms). | Function | Description | | -------------------------------------------------------------- | ----------------------------------------------------- | | `addEmail(userId, email, "Otp" \| "MagicLink")` | Send a verification code or link to an email address. | | `verifyEmail(userId, code, "Otp" \| "MagicLink")` | Confirm it. | | `addPhoneNumber(userId, phone, strategy)` | Send a code or link by SMS. | | `verifyPhoneNumber(userId, code, strategy)` | Confirm it. | | `requestPasswordReset(username, "email" \| "phone")` | Send a reset code. | | `completePasswordReset(username, code, newPassword, provider)` | Set the new password. | | `passwordlessLogin(username, provider)` | Send a login code. | | `completePasswordlessLogin(username, code, provider)` | Log in with the code. Returns a `UserSession`. | ```typescript await Auth.passwordlessLogin("ada@example.com", "email"); const session = await Auth.completePasswordlessLogin("ada@example.com", "123456", "email"); ``` ## Administration With an API key or identity: | Function | Description | | ---------------------------------------------------------------------- | --------------------------------------- | | `get(userId)`, `getAll(queryParams?)` | Read users. | | `updatePassword(userId, {password})` | Change a password. | | `updateUsername(userId, username)` | Change a username. | | `ban(userId, bannedUntil)` | Block logins until a date. | | `deactivateUserTokens(userId, date)` | Invalidate tokens issued before a date. | | `remove(userId)` | Delete a user. | | `policy.attach(userId, policyIds)`, `policy.detach(userId, policyIds)` | Manage policies. | --- # @spica-devkit/identity > Log identities in, handle two-factor challenges, and manage identities, their policies and login strategies. `@spica-devkit/identity` works with [identities](https://docs.spicaengine.com/auth/identities), the accounts of your team. Use it in internal tools and automation. ```bash npm install @spica-devkit/identity ``` ```typescript import * as Identity from "@spica-devkit/identity"; Identity.initialize({apikey: process.env.SPICA_API_KEY, publicUrl: "https://api.example.com/api"}); ``` ## Log in ```typescript const result = await Identity.login("editor", "a-long-random-password", 3600); if (Identity.isChallenge(result)) { const code = await askUserForTotpCode(result.show()); const token = await result.answer(code); } else { const token = result; } ``` `login` returns the JWT, or a challenge when the identity has [two-factor authentication](https://docs.spicaengine.com/auth/two-factor). `show()` returns the challenge text and `answer(code)` resolves to the token. | Function | Description | | ------------------------------------------------------- | --------------------------------------- | | `login(identifier, password, tokenLifeSpan?, headers?)` | Log in. Returns a token or a challenge. | | `isChallenge(result)` | Tell the two apart. | | `verifyToken(token, baseUrl?, headers?)` | Verify a token and return its payload. | | `getStrategies()` | List login strategies. | | `loginWithStrategy(strategyId)` | Start a SAML login. | ## Manage identities | Function | Description | | ------------------------------------------------------------------------------ | --------------------------------------------- | | `get(id)`, `getAll(queryParams?)` | Read identities. | | `insert({identifier, password})` | Create an identity. | | `update(id, identity)` | Update an identity. | | `remove(id)`, `removeMany(ids)` | Delete identities. | | `policy.attach(identityId, policyIds)`, `policy.detach(identityId, policyIds)` | Manage policies. | | `authfactor.list()` | Available second factors. | | `authfactor.register(identityId, {type: "totp", config: {}})` | Start enabling a factor. Returns a challenge. | | `authfactor.unregister(identityId)` | Disable two-factor authentication. | --- # @spica-devkit/storage > Upload, download, list, rename, replace and delete storage objects from browsers, Node.js and functions. ```bash npm install @spica-devkit/storage ``` ```typescript import * as Storage from "@spica-devkit/storage"; Storage.initialize({apikey: process.env.SPICA_API_KEY, publicUrl: "https://api.example.com/api"}); ``` ## Upload In a browser, pass `File` objects. In Node.js, pass buffers with a name and content type: ```typescript // Browser const input = document.querySelector("input[type=file]"); const objects = await Storage.insertMany(input.files, progress => console.log(Math.round((progress.loaded / progress.total) * 100), "%") ); // Node.js or functions const object = await Storage.insert({ name: "reports/2026-11.csv", contentType: "text/csv", data: Buffer.from(csv) }); object.url; ``` ## API | Function | Description | | -------------------------------------- | -------------------------------------------------------------------- | | `insert(file, onUploadProgress?)` | Upload one object. | | `insertMany(files, onUploadProgress?)` | Upload several objects. | | `get(id)` | Get an object's metadata. | | `getAll(queryParams?)` | List objects. Accepts `filter`, `sort`, `limit`, `skip`, `paginate`. | | `download(id, {onDownloadProgress?})` | Download the content: a `Blob` in browsers, a stream in Node.js. | | `update(id, file, onUploadProgress?)` | Replace the content. | | `updateMeta(id, {name})` | Rename. | | `remove(id)`, `removeMany(ids)` | Delete objects. | ```typescript const stream = await Storage.download(object._id); stream.pipe(fs.createWriteStream("report.csv")); ``` Storage endpoints accept identities and API keys. See [Storage](https://docs.spicaengine.com/storage) for strategies, folders and access control. --- # @spica-devkit/database > Get a native MongoDB connection inside Spica functions for advanced queries, and understand why the APIs are usually the better choice. `@spica-devkit/database` gives functions a native [MongoDB driver](https://www.mongodb.com/docs/drivers/node/) connection to Spica's database. It only works inside Spica functions on MongoDB instances. ```bash npm install @spica-devkit/database ``` ```javascript import {database, ObjectId} from "@spica-devkit/database"; export default async function () { const db = await database(); const posts = db.collection(`bucket_${process.env.POSTS_BUCKET_ID}`); return posts .aggregate([ {$match: {status: "published"}}, {$group: {_id: "$author", count: {$sum: 1}}}, {$sort: {count: -1}}, {$limit: 5} ]) .toArray(); } ``` | Export | Description | | --------------- | ----------------------------------------------------------- | | `database()` | Connects (once per worker) and returns the MongoDB `Db`. | | `ObjectId` | MongoDB's `ObjectId` class. | | `close(force?)` | Close the connection. Called for you when the worker stops. | | `isConnected()` | Whether a connection is open. | Bucket documents live in collections named `bucket_`. ## Before you use it Writing to the database directly skips everything the API does: - No schema validation, defaults or [rules](https://docs.spicaengine.com/buckets/rules). - No history, activity records or response cache invalidation. - Hashed and encrypted properties are stored in their protected form. - The internal data layout can change between releases. For that reason the package prints a `FootgunWarning` on first use. Prefer [`@spica-devkit/bucket`](https://docs.spicaengine.com/devkit/bucket) with an API key, and reserve direct access for read-only analytics such as aggregations. Set the `NO_DEVKIT_DATABASE_WARNING` environment variable on the function to silence the warning once you have made that choice. `--experimental-function-devkit-database-cache` makes repeated connections faster. --- # @spica-devkit/sync > Plan and apply Spica resource files from your own services, such as a deployment service that syncs a project from a git commit. `@spica-devkit/sync` is the engine behind `spica plan` and `spica apply`, as a library. Use it when you build your own deployment flow: download a repository archive, show the plan to a person for approval, and apply exactly what they approved. Nothing has to be written to disk. ```bash npm install @spica-devkit/sync ``` ## Example ```typescript import {apply, plan, readTarball} from "@spica-devkit/sync"; const connection = {url: "https://api.example.com/api", authorization: `APIKEY ${process.env.SPICA_API_KEY}`}; // 1. Read the resource files of a commit, for example from GET /repos/{owner}/{repo}/tarball/{sha} const archive = await fetch(tarballUrl, {headers: {Authorization: `Bearer ${githubToken}`}}); const files = await readTarball(archive.body, {path: "spica"}); // 2. Plan. The result is plain JSON: store it and show it for review. const reviewed = await plan({connection, files}); console.log(reviewed.totals); // {creates, updates, deletes} // 3. Apply after approval, with the same files. const result = await apply({connection, files, fingerprint: reviewed.fingerprint}); console.log(result.status); // "succeeded" | "partial" | "failed" | "outdated" ``` `apply` plans again first and only applies when the new plan has the same `fingerprint` as the reviewed one. When the files or the instance changed in between, nothing is applied and the result has the status `outdated` and the new plan. ## API | Export | Description | | ------------------------------ | -------------------------------------------------------------------------------- | | `plan(options)` | Compare `files` with the instance and resolve to a JSON-serializable plan. | | `apply(options)` | Apply when the plan still matches `options.fingerprint`. | | `readTarball(input, options?)` | Stream a (gzipped) tar archive and keep only the resource files, in memory. | | `SpicaRequestError` | Rejection type for failed requests, with `status` and `data` but no credentials. | ### `plan` and `apply` options | Option | Description | | --------------- | ------------------------------------------------------------------------------------- | | `connection` | `{url, authorization}`. | | `files` | A `Map` or object keyed by project-relative path, such as `bucket/Posts/schema.yaml`. | | `modules` | Limit to some modules. | | `concurrency` | Parallel requests, default `10`. | | `maxDiffLength` | Diffs longer than this are listed in `omittedDiffs` instead, default `200000`. | | `fingerprint` | `apply` only: the fingerprint of the reviewed plan. | | `abortOnError` | `apply` only: stop at the first failure. | ### `readTarball` options | Option | Default | Description | | ----------------- | ------- | ---------------------------------------------------------------------------------------------------- | | `path` | | Project folder inside the repository. | | `stripComponents` | `1` | Leading folders to remove, such as the `--/` folder of GitHub and GitLab archives. | | `maxFileBytes` | 5 MiB | Largest accepted file. | | `maxTotalBytes` | 50 MiB | Largest accepted total. | | `maxFiles` | `10000` | Most accepted files. | Files that aren't resources are skipped without being buffered. A truncated archive is rejected, so a partial download can never be planned as a set of deletions. The file format is the same as the CLI's. See [Resources as code](https://docs.spicaengine.com/cli/resources-as-code). --- # @spica-devkit/testing > Start a disposable Spica instance from your test suite, install your project's resources, reset data between tests and tear it down. `@spica-devkit/testing` starts a minimal Spica instance in Docker for end-to-end tests: a single-node MongoDB replica set and the API container, without the panel or an ingress. It installs your project's [resource files](https://docs.spicaengine.com/cli/resources-as-code) and works with any test framework. ```bash npm install --save-dev @spica-devkit/testing ``` Docker must be running. The sync engine is bundled, so you don't need the CLI. ## Example with Jest or Vitest ```typescript import {start} from "@spica-devkit/testing"; import * as Bucket from "@spica-devkit/bucket"; let spica; beforeAll(async () => { spica = await start({version: "0.22.1", resourcePath: "./"}); const response = await fetch(`${spica.publicUrl}/passport/identify`, { method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify({identifier: "spica", password: "spica"}) }); const {token} = await response.json(); Bucket.initialize({identity: token, publicUrl: spica.publicUrl}); }, 180_000); afterEach(() => spica.reset(["bucket-data"])); afterAll(() => spica.teardown()); test("published posts are listed", async () => { await Bucket.data.insert(POSTS_BUCKET_ID, {title: "Hello", slug: "hello", status: "published"}); const posts = await Bucket.data.getAll(POSTS_BUCKET_ID); expect(posts).toHaveLength(1); }); ``` ## `start(options?)` | Option | Default | Description | | ------------------------ | ------------------ | ---------------------------------------------------------------------------------- | | `version` | `"latest"` | `spicaengine/api` image tag. | | `mongoVersion` | `"8.0"` | `mongo` image tag. | | `resourcePath` | `"./"` | Folder with CLI-format resources (`bucket/`, `function/`, ...). | | `installResources` | `true` | `true`, `false`, or a selection such as `{bucket: ["Posts"], function: ["seed"]}`. | | `port` | Free port | Host port of the API. | | `name` | Generated | Name used to label containers. | | `identifier`, `password` | `"spica"` | Default identity credentials. | | `masterKey` | Random | `--master-key` of the API. | | `apiOptions` | `{}` | Extra API options, such as `{"activity-stream": false}`. | | `imagePullPolicy` | `"if-not-present"` | `"always"` pulls images every time. | | `readyTimeoutMs` | `120000` | How long to wait for the API to accept logins. | Installing only what a test file needs keeps boot times short, because every installed function is built. ## The returned handle | Member | Description | | ----------------- | -------------------------------------------------------------------------- | | `publicUrl` | API base URL, such as `http://localhost:54231`. There is no `/api` suffix. | | `waitForReady()` | Wait until the API accepts logins. | | `reset(modules?)` | Wipe state between tests. | | `teardown()` | Remove every container, network and volume of the instance. | ### `reset(modules)` | Module | Effect | | --------------- | ------------------------------------------------------------------------ | | `bucket-data` | Drops every bucket's documents. Schemas are kept. | | `bucket` | Drops documents and bucket schemas. | | `identity` | Deletes identities except the default one, and refresh tokens. | | `user` | Deletes users. | | `apikey` | Deletes API keys. | | `function` | Deletes function records. Loaded functions keep running until a restart. | | `storage` | Deletes storage metadata. Files stay on the volume. | | `all` (default) | All of the above. | Resets drop MongoDB collections directly, which is fast but bypasses the API. Prefer `bucket-data`, `identity` and `storage` between tests. --- # Self-hosting > Choose how to run Spica in production, what every deployment needs, and where to find the configuration reference. Spica is distributed as Docker images, so it runs anywhere containers run. Pick the setup that matches your team: - [Docker Compose](https://docs.spicaengine.com/self-hosting/docker): One machine, a few containers. Good for small production workloads, staging and demos. - [Kubernetes with Helm](https://docs.spicaengine.com/self-hosting/kubernetes): The official chart, with database, ingress, probes, secrets, migrations and scaling. - [Local with the CLI](https://docs.spicaengine.com/cli/local-projects): spica project start for development on your machine. ## Images | Image | Contents | | ---------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | | `spicaengine/api` | The API. Entry point `node src/main.js`, configured with [options](https://docs.spicaengine.com/self-hosting/configuration). | | `spicaengine/panel` | The admin panel, served by nginx on port 80. | | `spicaengine/postgres` | PostgreSQL with the `pg_cron` extension, for PostgreSQL deployments. Tags look like `18-`. | | `spicaengine/migrate` | Database migrations, run by the Helm chart before upgrades. | | `spicaengine/mongoreplicationcontroller` | Initializes and maintains MongoDB replica sets in Kubernetes. | Tags follow Spica releases (for example `0.22.1`). Pin a version in production. ## What every deployment needs | Requirement | Why | | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | | A database | MongoDB as a replica set (even with one node), or PostgreSQL. See [MongoDB and PostgreSQL](https://docs.spicaengine.com/self-hosting/databases). | | A master key | All encryption and signing secrets are derived from it. Generate a long random value and keep it safe. | | A public URL | `--public-url` must be the URL clients use, including `/api` when the API is served under that path. | | One host for panel and API | The panel calls the API at `/api` on its own origin. Route `/` to the panel and `/api` to the API. | | Persistent storage | Mount a volume at `--persistent-path`, or use S3/GCS for storage and function sources. | | TLS | Terminate HTTPS at your ingress or load balancer. Refresh token cookies require it. | | WebSockets | Allow upgrades on `/api` for realtime streams and the firehose. | ## Next steps - [API configuration reference](https://docs.spicaengine.com/self-hosting/configuration) - [Helm values reference](https://docs.spicaengine.com/self-hosting/helm-values) - [Production checklist](https://docs.spicaengine.com/self-hosting/production-checklist) --- # Docker Compose > Run Spica in production on a single machine with Docker Compose, a MongoDB replica set and an nginx gateway. This setup runs Spica on one machine: MongoDB, the API, the panel and an nginx gateway that serves the panel at `/` and the API at `/api`. ## Files ```yaml title="compose.yaml" services: mongo: image: mongo:8.0 command: ["--replSet", "rs0", "--bind_ip_all"] volumes: - mongo-data:/data/db healthcheck: test: ["CMD", "mongosh", "--quiet", "--eval", "try { rs.status().ok } catch (e) { rs.initiate({_id: 'rs0', members: [{_id: 0, host: 'mongo:27017'}]}).ok }"] interval: 5s timeout: 10s retries: 20 restart: unless-stopped api: image: spicaengine/api:${SPICA_VERSION:-0.22.1} depends_on: mongo: condition: service_healthy environment: MASTER_KEY: ${SPICA_MASTER_KEY:?Set SPICA_MASTER_KEY} PASSPORT_DEFAULT_IDENTITY_PASSWORD: ${SPICA_ADMIN_PASSWORD:?Set SPICA_ADMIN_PASSWORD} command: - --port=4300 - --database-uri=mongodb://mongo:27017/?replicaSet=rs0 - --database-name=spica - --database-replica-set=rs0 - --public-url=${SPICA_PUBLIC_URL:-http://localhost:8080/api} - --persistent-path=/data volumes: - spica-data:/data restart: unless-stopped panel: image: spicaengine/panel:${SPICA_VERSION:-0.22.1} restart: unless-stopped gateway: image: nginx:latest depends_on: [api, panel] ports: - "8080:80" volumes: - ./gateway.conf:/etc/nginx/conf.d/default.conf:ro restart: unless-stopped volumes: mongo-data: spica-data: ``` ```text title="gateway.conf" server { listen 80; client_max_body_size 35m; location / { proxy_pass http://panel:80/; proxy_set_header Host $host; } location /api/ { proxy_pass http://api:4300/; proxy_http_version 1.1; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_read_timeout 3600s; } } ``` ```dotenv title=".env" SPICA_VERSION=0.22.1 SPICA_MASTER_KEY= SPICA_ADMIN_PASSWORD= SPICA_PUBLIC_URL=https://admin.example.com/api ``` The trailing slashes in `proxy_pass` matter: the gateway strips `/api` before forwarding, so the API serves its routes at the root while `--public-url` keeps the `/api` suffix. ## Start ```bash docker compose up -d docker compose ps curl http://localhost:8080/api/status/live ``` ```json {"status": "ok"} ``` Open `http://localhost:8080` and log in as `spica` with `SPICA_ADMIN_PASSWORD`. ## Going to production - **TLS.** Put the gateway behind a TLS-terminating proxy or load balancer, or add a certificate to the nginx config. Set `SPICA_PUBLIC_URL` to the HTTPS URL. - **Secrets.** Keep `.env` out of git. Back up `SPICA_MASTER_KEY`: without it, encrypted data and secrets can't be read. - **Backups.** Back up the `mongo-data` volume (or use `mongodump`) and the `spica-data` volume, which holds uploaded files and function sources. - **Upload size.** Keep `client_max_body_size` in line with `--storage-object-size-limit`. - **Options.** Add any [API option](https://docs.spicaengine.com/self-hosting/configuration) to the `api` service's `command` or as an environment variable, for example `BUCKET_CACHE: "true"`. - **Logs.** `docker compose logs -f api`. Add `--access-logs` and `--function-worker-log-output=database,stdout` to send more to stdout. ## PostgreSQL instead of MongoDB Replace the `mongo` service with PostgreSQL, load `pg_cron`, and change the API's database options. These are the same settings `spica project start --database-type postgresql` uses: ```yaml postgres: image: spicaengine/postgres:18-0.22.1 command: ["postgres", "-c", "shared_preload_libraries=pg_cron", "-c", "cron.use_background_workers=on", "-c", "cron.database_name=spica"] environment: POSTGRES_USER: spica POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD} POSTGRES_DB: spica volumes: - postgres-data:/var/lib/postgresql restart: unless-stopped ``` ```yaml environment: POSTGRES_USERNAME: spica POSTGRES_PASSWORD: ${POSTGRES_PASSWORD} command: - --port=4300 - --database-type=postgresql - --database-uri=postgres://postgres:5432/spica - --public-url=${SPICA_PUBLIC_URL:-http://localhost:8080/api} - --persistent-path=/data ``` ## Upgrading 1. Read the release notes of the new version. 2. Back up the database and volumes. 3. Change `SPICA_VERSION` and run `docker compose pull && docker compose up -d`. Releases that change stored data ship a migration in the `spicaengine/migrate` image, which the Helm chart runs automatically. Check the release notes when you upgrade with Compose. --- # Kubernetes with Helm > Install Spica on Kubernetes with the official Helm chart, configure database, secrets, ingress and storage, and scale and upgrade it. The official Helm chart installs the API, the panel, a MongoDB replica set or PostgreSQL, an ingress, secrets and a migration job that runs before upgrades. ## Install ```bash helm repo add spica https://spica-charts.storage.googleapis.com helm repo update helm search repo spica ``` Create a values file: ```yaml title="values.yaml" application: publicHost: https://admin.example.com masterKey: "" defaultPassword: "" database: type: mongodb replicas: 3 storageSize: 20Gi spicaUsername: spica spicaPassword: "" rootUsername: root rootPassword: "" replicaAuthKey: "" ingress: ingressClassName: nginx hosts: - name: admin.example.com application: / api: /api tls: - hosts: [admin.example.com] secretName: admin-example-com-tls ``` ```bash helm install spica spica/spica --namespace spica --create-namespace -f values.yaml --version 0.22.1 ``` When the release is ready, the chart prints where the panel is and the credentials of the default identity: ```text Web Controller is open at https://admin.example.com/ Credentials are: # Username: spica # Password: ``` ## How it fits together | Resource | Purpose | | ----------------------------------------------------- | ----------------------------------------------------------------------------------------------- | | `StatefulSet` or `Deployment` `-application` | The API (port `4300`, gRPC `50051`) and the panel, as two containers of one pod. | | `Service` `-application` | Exposes the panel and the API inside the cluster. | | `StatefulSet` `-database` | MongoDB nodes, or a single PostgreSQL node. | | `Job` `-replication-controller` | Initializes the MongoDB replica set. | | `Ingress` `-application` | Routes `application` paths to the panel and `api` paths to the API. | | `Secret`s | The master key or individual secrets, and database credentials. | | `Job` `-migrate` | Runs on upgrades only, as a `pre-upgrade` hook that migrates stored data before new pods start. | The API's public URL is `application.publicHost` + `application.apiBaseUrl` (`/api/` by default). Probes use `/status/live` and `/status/ready`. ## Secrets Provide **either** `application.masterKey`, from which every secret is derived, **or** all individual secrets: `secret`, `bucketDataHashSecret`, `bucketDataEncryptionSecret`, `secretModuleEncryptionSecret`, `userVerificationHashSecret`, `userProviderEncryptionSecret`, `userProviderHashSecret` and `refreshTokenHashSecret`. Individual values override the derived ones. Secrets are stored in a Kubernetes `Secret` and reused on upgrades, so you don't have to pass them again. Rendering fails with a clear message when something is missing: ```text Error: execution error at (spica/templates/applicationsecrets.yaml:35:36): masterKey is absent: .Values.application.secret is required ``` > **Danger** > > Keep the master key in your secret manager as well. If the Kubernetes secret is lost, encrypted data can't be recovered without it. ## Choosing the database ```yaml database: type: postgresql storageSize: 20Gi spicaUsername: spica spicaPassword: "" rootUsername: postgres rootPassword: "" ``` PostgreSQL runs as a single node and ignores `database.replicas`. The image (`database.postgresImage`, `spicaengine/postgres` by default) must include `pg_cron`. The engine can't be changed after installation. See [MongoDB and PostgreSQL](https://docs.spicaengine.com/self-hosting/databases). ## Passing API options Any [API option](https://docs.spicaengine.com/self-hosting/configuration) can be added with `application.args`: ```yaml application: args: - --bucket-cache=true - --function-timeout=120 - --access-logs=true responseHeaders: X-Frame-Options: DENY Strict-Transport-Security: max-age=31536000 ``` The chart sets the port, database, public URL, persistent path, default password and replication options itself. ## Storage and scaling `application.diskAccessMode` decides how `/data` (uploaded files and function sources) is stored: | Value | Workload | `/data` | Use when | | ------------------------- | ----------- | --------------------------- | ----------------------------------------------------------------- | | `ReadWriteOnce` (default) | StatefulSet | A volume per pod | One replica. | | `ReadWriteMany` | Deployment | One shared volume | Several replicas with an RWX storage class (NFS, EFS, Filestore). | | `None` | Deployment | `emptyDir`, lost on restart | Several replicas with S3 or GCS for files and function sources. | A horizontally scaled setup with object storage: ```yaml application: replicas: 3 diskAccessMode: None serviceAccountName: spica args: - --storage-strategy=awss3 - --awss3-bucket-name=acme-spica-files - --function-asset-storage-strategy=awss3 - --function-asset-awss3-bucket-name=acme-spica-functions ``` With more than one replica, the chart turns on `--replication` automatically. On EKS, give the service account an IAM role (IRSA) and leave the credential file options out. The AWS SDK picks the role up. ## Ingress ```yaml ingress: ingressClassName: nginx annotations: nginx.ingress.kubernetes.io/proxy-body-size: 35M nginx.ingress.kubernetes.io/client-body-buffer-size: 35m nginx.ingress.kubernetes.io/rewrite-target: /$1 hosts: - name: admin.example.com application: / api: /api tls: - hosts: [admin.example.com] secretName: admin-example-com-tls ``` The default annotations target ingress-nginx. Keep the `rewrite-target` annotation, which strips the `/api` prefix, or replicate it for another controller. Raise the body size when you raise `--storage-object-size-limit`. ## Upgrade ```bash helm repo update helm upgrade spica spica/spica --namespace spica -f values.yaml --version ``` The migration job runs first, then pods are replaced. Back up the database before upgrading, and read the release notes. ## Uninstall ```bash helm uninstall spica --namespace spica ``` Volume claims created by the StatefulSets (database data, and API data with `ReadWriteOnce`) are kept. Delete them yourself when you no longer need the data. See the [Helm values reference](https://docs.spicaengine.com/self-hosting/helm-values) for every value. --- # MongoDB and PostgreSQL > Run Spica on MongoDB or PostgreSQL, set each one up correctly, and know the differences your applications will see. Spica runs on either **MongoDB** or **PostgreSQL**. You choose the engine when you create an instance with `--database-type`, and it stays the same for the instance's lifetime. Both engines support buckets, functions, passport, storage, realtime and the rest of the platform. ## MongoDB ```bash --database-type=mongodb \ --database-uri="mongodb://mongo-0,mongo-1,mongo-2/?replicaSet=rs0" \ --database-name=spica \ --database-replica-set=rs0 ``` - MongoDB **must run as a replica set**, even with a single node. Spica uses change streams for realtime, triggers and webhooks. - Credentials can be passed with `MONGODB_USERNAME` and `MONGODB_PASSWORD`. - Tune `--database-pool-size`, `--database-read-preference` and `--database-change-stream-await-time` for your load. ## PostgreSQL ```bash --database-type=postgresql \ --database-uri="postgres://postgres:5432/spica" ``` - Use the `spicaengine/postgres` image, or a PostgreSQL server with the `pg_cron` extension. Spica uses it to expire logs, statuses, tokens and other short-lived records. - Credentials can be passed with `POSTGRES_USERNAME` and `POSTGRES_PASSWORD`. - `--database-name` is ignored; the database is part of the URI. ## Differences your applications see | Topic | MongoDB | PostgreSQL | | ---------------------------- | -------------------------------------------- | ------------------------------------------------------------------------------------------------------------- | | Resource ids | `_id`, an ObjectId string | `id`, a UUIDv7 string | | Document keys | `_id` on every document | The bucket's `primary` property, which must be `uuid`, `integer`, `bigint` or `string` and can be `generated` | | Extra property types | | `uuid`, `integer`, `bigint` (returned as a string) | | Bucket filters | Expressions and JSON (MongoDB query) filters | Expressions only | | Translated properties | Any property type | Scalar types | | Relations inside arrays | Supported | Not supported | | Index options | Any MongoDB index option | `unique`, `sparse`, `background`. `2dsphere` indexes have one property and aren't unique. | | Document limit with `remove` | Supported | Not with a `string` primary key | | GraphQL | Supported | Not available | | `@spica-devkit/database` | Supported | Not available | | `@spica-devkit/testing` | Supported | MongoDB only | A PostgreSQL bucket and a document look like this: ```json {"id": "01a2235d-7c41-789b-b7f5-fb7beb95c31e", "title": "Posts", "primary": "id", "properties": {"id": {"type": "bigint", "options": {"generated": true}}}} ``` ```json {"id": "1", "slug": "hello-spica", "title": "Hello Spica", "views": 42, "author": "01a2235d-7c6a-7fab-b705-48e72471385d"} ``` ## Writing portable code If your code must run on both engines: - Use [expression filters](https://docs.spicaengine.com/buckets/querying#expression-filters) everywhere. - Read ids through a helper that checks `_id` and then `id`. - Avoid engine-only features from the table above. ## Choosing an engine Choose the database your team already operates well. MongoDB suits flexible, nested documents and makes JSON filters and GraphQL available. PostgreSQL suits teams that standardize on relational databases, want typed primary keys, or run managed PostgreSQL services. ## Running the database | Setup | MongoDB | PostgreSQL | | ------- | -------------------------------- | ------------------------------------------------------- | | CLI | `spica project start ` | `spica project start --database-type postgresql` | | Helm | `database.type: mongodb` | `database.type: postgresql` | | Managed | MongoDB Atlas or any replica set | Any PostgreSQL with `pg_cron` | Back up the database regularly, together with the volume or bucket that holds files and function sources. --- # API configuration reference > Every startup option of the Spica API, grouped by area, with defaults, environment variables and validation rules. The API is configured with command-line options: ```bash node src/main.js --database-uri=mongodb://db:27017 --database-name=spica \ --public-url=https://api.example.com/api --master-key= --port=4300 ``` **Environment variables.** Every option can also be given as an environment variable: upper case, with `_` instead of `-`. For example `--database-uri` becomes `DATABASE_URI` and `--bucket-cache-ttl` becomes `BUCKET_CACHE_TTL`. Command-line options take precedence. **Booleans** accept `--flag`, `--flag=true` and `--flag=false`. **Arrays** accept repeated values, for example `--cors-allowed-origins https://a.com https://b.com`. Run `node src/main.js --help` in the API container to print every option of your version. ## Required | Option | Description | | ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `--database-uri` | Database connection URL. | | `--database-name` | Database name. Required for MongoDB, ignored for PostgreSQL. | | `--public-url` | The URL clients use to reach the API, for example `https://example.com/api`. Used for storage URLs, OAuth redirects, magic links and token issuers. Alias: `--public-host`. | | `--master-key` | Secret from which every other secret is derived. Required unless you provide all [secrets](#secrets) one by one. | ## Server | Option | Default | Description | | --------------------------- | --------- | ------------------------------------------------------------------------------------------------------ | | `--port`, `-p` | `80` | HTTP port. | | `--persistent-path` | `/tmp` | Directory for persistent data such as function code and default-strategy storage. Mount a volume here. | | `--cert-file`, `--key-file` | | Serve HTTPS directly with this certificate and key. Usually TLS is terminated by the ingress instead. | | `--trust-proxy` | `true` | Trust `X-Forwarded-*` headers: `true`, `false`, a number of hops, or a comma-separated list of IPs. | | `--payload-size-limit` | `15` | Maximum request body size in MiB. | | `--common-log-lifespan` | `2592000` | Seconds after which logs, activity and status records expire (30 days). | ## Database | Option | Default | Description | | ----------------------------------------- | --------- | ----------------------------------------------------------------------------------------------------- | | `--database-type` | `mongodb` | `mongodb` or `postgresql`. Fixed for the life of the instance. | | `--database-replica-set`, `--replica-set` | | MongoDB replica set name. | | `--database-pool-size` | `50` | Connections opened to the database. | | `--database-read-preference` | `primary` | MongoDB read preference: `primary`, `primaryPreferred`, `secondary`, `secondaryPreferred`, `nearest`. | | `--database-change-stream-await-time` | `1000` | Milliseconds MongoDB waits for new change stream data before returning an empty batch. | | Environment variable | Effect | | ---------------------------------------- | --------------------------------- | | `MONGODB_USERNAME`, `MONGODB_PASSWORD` | Injected into the MongoDB URI. | | `POSTGRES_USERNAME`, `POSTGRES_PASSWORD` | Injected into the PostgreSQL URI. | ## Secrets When `--master-key` (or `MASTER_KEY`) is set, every secret below is derived from it unless you set it explicitly. Without a master key, all of them are required. | Option | Environment variable | Protects | | ----------------------------------- | --------------------------------- | -------------------------------------------------- | | `--passport-secret`, `--secret` | `PASSPORT_SECRET` | Signing of identity and user JWTs. | | `--bucket-data-hash-secret` | `BUCKET_DATA_HASH_SECRET` | `hash` properties and lookups of `encrypted` ones. | | `--bucket-data-encryption-secret` | `BUCKET_DATA_ENCRYPTION_SECRET` | `encrypted` properties. | | `--secret-module-encryption-secret` | `SECRET_MODULE_ENCRYPTION_SECRET` | Function secrets. | | `--user-verification-hash-secret` | `USER_VERIFICATION_HASH_SECRET` | Verification codes. | | `--user-provider-encryption-secret` | `USER_PROVIDER_ENCRYPTION_SECRET` | Users' emails, phone numbers and OAuth attributes. | | `--user-provider-hash-secret` | `USER_PROVIDER_HASH_SECRET` | Lookups of users' providers. | | `--refresh-token-hash-secret` | `REFRESH_TOKEN_HASH_SECRET` | Stored refresh tokens. | > **Danger** > > Never change the master key or a derived secret on an instance that has data. Encrypted values become unreadable, hashes stop matching and every session ends. Store the master key in a secret manager. ## Buckets | Option | Default | Description | | --------------------- | ------- | ----------------------------------------------------------------------------- | | `--bucket-hooks` | `true` | Enable bucket triggers for functions. | | `--bucket-history` | `true` | Enable document history. | | `--bucket-graphql` | `false` | Serve GraphQL at `/graphql` (MongoDB only). | | `--bucket-cache` | `false` | Cache bucket data responses in memory. | | `--bucket-cache-ttl` | `60` | Cache lifetime in seconds. Must be positive. | | `--bucket-data-limit` | | Maximum number of documents across all buckets. | | `--activity-stream` | `true` | Record the [activity stream](https://docs.spicaengine.com/platform/activity). | ## Passport | Option | Default | Description | | ---------------------------------------------------------------- | ------------------------ | -------------------------------------------------------------------------------- | | `--passport-default-strategy` | `IDENTITY` | Default authentication strategy: `IDENTITY` or `APIKEY`. | | `--passport-default-identity-identifier` | `spica` | Identifier of the default identity. | | `--passport-default-identity-password` | `spica` | Password of the default identity. **Change it.** | | `--passport-default-identity-policies` | All full access policies | Policies of the default identity. | | `--passport-identity-token-expires-in` | `172800` | Identity token lifetime in seconds (2 days). | | `--passport-identity-token-expiration-seconds-limit` | Same as above | Longest lifetime a client may request. Can't be lower than the default lifetime. | | `--passport-identity-refresh-token-expires-in` | `259200` | Identity refresh token lifetime (3 days). | | `--passport-identity-password-history-limit` | `0` | Previous passwords that can't be reused. | | `--passport-identity-failed-login-attempt-limit` | `0` | Failed logins before a block. `0` disables it. | | `--passport-identity-block-duration-after-failed-login-attempts` | `0` | Block duration in minutes. | | `--passport-identity-limit` | | Maximum number of identities. | | `--passport-user-token-expires-in` | `172800` | User token lifetime. | | `--passport-user-token-expiration-seconds-limit` | Same as above | Longest lifetime a client may request. | | `--passport-user-refresh-token-expires-in` | `259200` | User refresh token lifetime. | | `--passport-user-password-history-limit` | `0` | Previous passwords that can't be reused. | | `--passport-user-failed-login-attempt-limit` | `0` | Failed logins before a block. | | `--passport-user-block-duration-after-failed-login-attempts` | `0` | Block duration in minutes. | | `--passport-user-limit` | | Maximum number of users. | | `--passport-user-verification-code-expires-in` | `300` | Verification code lifetime in seconds. | | `--passport-saml-certificate-ttl` | Unlimited | Lifetime of the self-signed SAML certificate in seconds. | ## Functions | Option | Default | Description | | ----------------------------------------------- | ------------------------- | --------------------------------------------------------------------------------------------------- | | `--function-timeout` | `60` | Upper bound for function timeouts, in seconds. | | `--function-limit` | | Maximum number of functions. | | `--function-api-url` | `http://127.0.0.1:` | URL functions use to reach the API. | | `--function-builder` | `legacy` | `legacy` or `rollup`. See [Builders](https://docs.spicaengine.com/functions/dependencies#builders). | | `--function-builder-max-memory` | | Heap limit of the rollup builder in MB. | | `--function-worker-concurrency` | `2` | Parallel workers per function. Must be positive. | | `--function-worker-event-concurrency` | `100` | Upper bound for a function's `concurrencyPerWorker`. | | `--function-warm-workers-max` | `10` | Upper bound for a function's `warmWorkers`. `0` disables warm workers. | | `--function-worker-cutover-grace-ms` | `30000` | How long old workers keep serving while new code warms up. | | `--function-debug` | `false` | Start workers in debugging mode. | | `--function-logger` | `true` | Record log levels. | | `--function-worker-log-output` | `database` | `database`, `stdout`, or both separated by commas. | | `--function-invocation-logs` | `false` | Log every invocation to stdout. | | `--grpc-function-port` | `50051` | Port of the gRPC trigger server. | | `--function-grpc-max-message-size-bytes` | `26214400` | Maximum gRPC message size (25 MiB). | | `--experimental-function-devkit-database-cache` | `false` | Cache `@spica-devkit/database` connections. | ### Function source storage | Option | Default | Description | | ------------------------------------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------ | | `--function-asset-storage-strategy` | `default` | `default`, `awss3` or `gcs`. | | `--function-asset-path` | OS temp dir | Directory for function sources with `default`. Share it between replicas. | | `--function-asset-awss3-bucket-name` | | S3 bucket. Required with `awss3`. | | `--function-asset-awss3-credentials-path` | | JSON file with `accessKeyId`, `secretAccessKey`, `region`. Optional; the AWS default credential chain is used otherwise. | | `--function-asset-gcs-bucket-name` | | GCS bucket. Required with `gcs`. | | `--function-asset-gcs-service-account-path` | | Service account JSON. Required with `gcs`. | ## Storage | Option | Default | Description | | ------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------- | | `--storage-strategy` | `default` | `default`, `awss3` or `gcloud`. | | `--default-storage-path` | `storage` | Directory relative to `--persistent-path`. Must be relative. | | `--default-storage-public-url` | `--public-url` | Base URL used for object URLs with `default`. | | `--awss3-bucket-name` | | S3 bucket. Required with `awss3`. | | `--awss3-credentials-path` | | Credentials file. Optional; the AWS default credential chain (environment, EKS IRSA, instance profile) is used otherwise. | | `--gcloud-bucket-name` | | GCS bucket. Required with `gcloud`. | | `--gcloud-service-account-path` | | Service account JSON. Required with `gcloud`. | | `--storage-object-size-limit` | `35` | Maximum object size in MiB. | | `--storage-total-size-limit` | | Total storage limit in MB. | | `--resumable-upload-expires-in` | `172800000` | Milliseconds before unfinished resumable uploads are removed (2 days). | ## Mailer and SMS | Option | Default | Description | | ---------------------------------- | -------- | ------------------------ | | `--mailer-host`, `--mailer-port` | | SMTP server. | | `--mailer-secure` | `false` | Use TLS from the start. | | `--mailer-user`, `--mailer-pass` | | SMTP credentials. | | `--mailer-from` | | Default sender. | | `--sms-sender-strategy` | `twilio` | SMS provider. | | `--twilio-sms-service-account-sid` | | Or `TWILIO_ACCOUNT_SID`. | | `--twilio-sms-service-auth-token` | | Or `TWILIO_AUTH_TOKEN`. | | `--twilio-sms-service-from-number` | | Or `TWILIO_FROM_NUMBER`. | ## HTTP | Option | Default | Description | | ---------------------------------------------------- | -------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ | | `--cors-allowed-origins` | `*` | Allowed origins. | | `--cors-allowed-methods` | `*` | Allowed methods. | | `--cors-allowed-headers` | `Authorization`, `Content-Type`, `Accept-Language` | Allowed request headers. | | `--cors-allow-credentials` | `true` | `Access-Control-Allow-Credentials`. | | `--response-header` | | Headers added to every response, as `"Name: value"` pairs. Pass all of them to a single `--response-header`. | | `--cache-control-header`, `--x-frame-options-header` | | Deprecated. Use `--response-header`. | ```bash --response-header "X-Frame-Options: DENY" "Strict-Transport-Security: max-age=31536000" ``` ## Observability and scaling | Option | Default | Description | | --------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------ | | `--http-status-tracking` | `true` | Count requests and transferred bytes for `/status`. | | `--access-logs` | `false` | Log HTTP requests to stdout. | | `--access-logs-url-filter` | `.*` | Regex of URLs to log. | | `--access-logs-statuscode-filter` | `.*` | Regex of status codes to log. | | `--access-logs-proxy-request-id-header` | `x-request-id` | Header logged as `proxy_request_id`. | | `--replication` | `false` | Coordinate several API replicas. See [Replication](https://docs.spicaengine.com/platform/replication). | ## Validation The API refuses to start when options contradict each other, for example: - `--gcloud-service-account-path and --gcloud-bucket-name options must be present when --storage-strategy is set to 'gcloud'.` - `--default-storage-path must be relative.` - `--passport-user-token-expiration-seconds-limit(...) can not be less than --passport-user-token-expires-in(...)` - `passport-secret is required when the master-key is not provided` --- # Helm values reference > Every value of the Spica Helm chart for the application, database, images and ingress, with defaults. Defaults come from the chart's `values.yaml`. See [Kubernetes with Helm](https://docs.spicaengine.com/self-hosting/kubernetes) for how to use them. ## `application` | Value | Default | Description | | -------------------------------------------------------------------------------------------------------- | --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `publicHost` | | **Required.** Public origin, such as `https://admin.example.com`. | | `webBaseUrl` | `/` | Path of the panel. | | `apiBaseUrl` | `/api/` | Path of the API. The API's public URL is `publicHost` + `apiBaseUrl`. | | `replicas` | `1` | API and panel replicas. More than one turns on `--replication`. | | `masterKey` | | Master key. Required unless every individual secret is set. | | `secret` | | JWT signing secret (`PASSPORT_SECRET`). | | `bucketDataHashSecret`, `bucketDataEncryptionSecret` | | Secrets for hashed and encrypted bucket properties. | | `secretModuleEncryptionSecret` | | Encryption of function secrets. | | `userVerificationHashSecret` | | Hashing of verification codes. | | `userProviderEncryptionSecret`, `userProviderHashSecret` | | Protection of users' emails, phones and attributes. | | `refreshTokenHashSecret` | | Hashing of refresh tokens. | | `twilioAccountSid`, `twilioAuthToken`, `twilioFromNumber` | | Twilio credentials for SMS. | | `defaultPassword` | `spica` | Password of the default identity. **Change it.** | | `args` | `[]` | Extra [API options](https://docs.spicaengine.com/self-hosting/configuration). | | `responseHeaders` | `{}` | Headers added to every API response, as a map. | | `diskAccessMode` | `ReadWriteOnce` | `ReadWriteOnce` (StatefulSet and a volume per pod), `ReadWriteMany` (Deployment and a shared volume) or `None` (Deployment and `emptyDir`; requires S3 or GCS strategies). | | `storageSize` | `2Gi` | Size of the `/data` volume. | | `storageClass` | | Storage class of the `/data` volume. | | `apiResources`, `webResources` | `{}` | Resource requests and limits of the API and panel containers. | | `serviceAccountName` | `default` | Service account of the pod, for example for IRSA or Workload Identity. | | `podAnnotations` | `{}` | Annotations added to the pod. | | `apiStartupProbeInitialDelaySeconds` | `10` | Startup probe on `/status/live`. | | `apiStartupProbePeriodSeconds`, `apiStartupProbeTimeoutSeconds`, `apiStartupProbeFailureThreshold` | `5`, `3`, `24` | | | `apiLivenessProbePeriodSeconds`, `apiLivenessProbeTimeoutSeconds`, `apiLivenessProbeFailureThreshold` | `30`, `10`, `6` | Liveness probe on `/status/live`. | | `apiReadinessProbePeriodSeconds`, `apiReadinessProbeTimeoutSeconds`, `apiReadinessProbeFailureThreshold` | `10`, `10`, `6` | Readiness probe on `/status/ready`. | ## `database` | Value | Default | Description | | ---------------------------------------------------- | ------------------------------------ | ----------------------------------------------------------------------------- | | `type` | `mongodb` | `mongodb` or `postgresql`. Fixed for the life of the instance. | | `replicas` | `1` | MongoDB replica set members. Ignored for PostgreSQL, which runs one node. | | `replicaSetName` | `rs0` | MongoDB replica set name. | | `name` | `spica` | Database name. | | `version` | `8.0.4` (MongoDB), `18` (PostgreSQL) | Image tag of the database. | | `postgresImage` | `spicaengine/postgres` | PostgreSQL image. Must include `pg_cron`. | | `storageSize` | `2Gi` | Volume size per database node. | | `storageClass` | | Storage class of database volumes. | | `resources` | `{}` | Resource requests and limits. | | `spicaUsername`, `spicaPassword` | | Credentials the API uses. | | `rootUsername`, `rootPassword` | | Administrative credentials. | | `replicaAuthKey` | | MongoDB keyfile content shared by replica set members. | | `replicationControllerImage` | | Override of the replication controller image. | | `logLevel` | `0` | MongoDB log verbosity. | | `profilingLevel` | `1` | MongoDB profiler level. `1` records slow operations for the panel's profiler. | | `profilingSlowms` | `100` | Threshold of slow operations in milliseconds. | | `terminationGracePeriodSeconds` | `60` | Grace period on shutdown. | | `startupProbe*`, `livenessProbe*`, `readinessProbe*` | See `values.yaml` | Database probe timings. | ## `images` | Value | Default | | ----------------------- | ---------------------------------------- | | `api` | `spicaengine/api` | | `web` | `spicaengine/panel` | | `replicationcontroller` | `spicaengine/mongoreplicationcontroller` | | `migrate` | `spicaengine/migrate` | Image tags follow the chart's `appVersion`. ## `ingress` | Value | Default | Description | | ------------------ | ---------------------- | ----------------------------------------------------------------------------------------------------------------------- | | `hosts` | `[]` | Hosts with their paths: `{name, application, api}`, for example `{name: admin.example.com, application: /, api: /api}`. | | `tls` | `[]` | Standard Ingress TLS entries. | | `ingressClassName` | `nginx` | Ingress class. | | `annotations` | ingress-nginx defaults | `proxy-body-size: 15M`, `client-body-buffer-size: 15m`, `rewrite-target: /$1`. | --- # Production checklist > Security, reliability, performance and operations items to check before and after you put a Spica instance in front of real users. ## Security - [ ] The default identity's password is changed (`--passport-default-identity-password` or `application.defaultPassword`), or the default identity is removed. - [ ] Every team member has a personal identity with only the policies they need. - [ ] Identities with full access use [two-factor authentication](https://docs.spicaengine.com/auth/two-factor). - [ ] The master key is long, random, stored in a secret manager and backed up. - [ ] The API is served over HTTPS only, and `--public-url` uses `https://`. - [ ] `--cors-allowed-origins` lists your apps' origins instead of `*`. - [ ] Response headers such as `X-Frame-Options` and `Strict-Transport-Security` are set with `--response-header`. - [ ] No API key with write access, or read access to private data, is used in browsers or mobile apps. - [ ] Every bucket that users can reach has [read and write rules](https://docs.spicaengine.com/buckets/rules). - [ ] HTTP functions that change data use `authenticate`, and public ones use `rateLimit`. - [ ] Credentials used by functions are [secrets](https://docs.spicaengine.com/functions/environment), not environment variables. - [ ] Password policy, lockout and [rate limits](https://docs.spicaengine.com/auth/security) are configured for users. - [ ] Access tokens are short-lived and clients use refresh tokens. ## Data - [ ] The database runs with authentication. MongoDB runs as a replica set, preferably with three members. - [ ] Automated backups of the database, files and function sources exist, and a restore has been tested. - [ ] Buckets have [indexes](https://docs.spicaengine.com/buckets/advanced#indexes) for their common filters, sorts and rules. - [ ] Buckets that grow without bound (logs, notifications) have [document limits](https://docs.spicaengine.com/buckets/advanced#document-limits). - [ ] Uploaded files and function sources live on durable, shared storage when you run several replicas. ## Reliability and performance - [ ] Liveness and readiness probes use `/status/live` and `/status/ready`. - [ ] API containers have memory limits, and `--function-builder-max-memory` stays below them when you use the rollup builder. - [ ] Function timeouts match the real duration of their handlers. - [ ] Latency-sensitive functions use warm workers, and I/O-bound ones a higher `concurrencyPerWorker`. - [ ] Read-heavy public data is served with the bucket response cache or a CDN. - [ ] `--replication` is on when you run more than one API replica. - [ ] Your proxy allows WebSocket upgrades and long-lived connections on `/api`. - [ ] Your proxy's body size limit matches `--storage-object-size-limit` and `--payload-size-limit`. ## Operations - [ ] Resources are kept in git and deployed with [`spica plan` and `spica apply`](https://docs.spicaengine.com/cli/resources-as-code) from CI. - [ ] Access logs and function worker logs go to stdout and into your log platform. - [ ] Alerts exist for function errors, 5xx responses and database health. - [ ] You know how long logs and activity are kept (`--common-log-lifespan`) and it fits your audit needs. - [ ] Image versions are pinned, and upgrades are tested on staging first. - [ ] Unused identities, API keys and refresh tokens are reviewed and removed regularly. --- # Recipes > End-to-end scenarios that combine buckets, functions, authentication, storage, the CLI and the devkit to solve common problems. Each recipe solves a complete problem, from schema to deployment, and links to the reference pages for details. - [Headless CMS for a blog](https://docs.spicaengine.com/recipes/headless-cms-blog): Content model, editors, public read access and rebuild webhooks. - [User sign-up with email verification](https://docs.spicaengine.com/recipes/user-signup-verification): A sign-up endpoint, verification codes and password reset. - [Welcome email for new users](https://docs.spicaengine.com/recipes/welcome-email): React to new users with a database trigger and send an email over SMTP. - [Scheduled cleanup job](https://docs.spicaengine.com/recipes/scheduled-cleanup): Delete stale data every night in safe batches. - [CI/CD with GitHub Actions](https://docs.spicaengine.com/recipes/ci-cd-github-actions): Plan on pull requests, apply on merge. - [End-to-end tests](https://docs.spicaengine.com/recipes/e2e-testing): Test functions and rules against a disposable instance. - [User uploads on Amazon S3](https://docs.spicaengine.com/recipes/s3-media-uploads): Let users upload avatars through a function, stored on S3. --- # Headless CMS for a blog > Model posts and authors, let editors manage content in the panel, serve published posts to your website and trigger a rebuild on every change. In this recipe you build the content backend of a blog: editors write in the panel, the website reads published posts, and every change triggers a rebuild of the static site. ## 1. Model the content Create two buckets. With the [CLI](https://docs.spicaengine.com/cli/resources-as-code), add these files and run `spica apply`: ```yaml title="bucket/Authors/schema.yaml" title: Authors description: People who write posts primary: name properties: name: type: string title: Name bio: type: textarea title: Bio options: translate: true avatar: type: storage title: Avatar required: - name ``` Apply it, note the bucket id of Authors (`spica fetch` writes it into the file), and create the posts bucket that references it: ```yaml title="bucket/Posts/schema.yaml" title: Posts description: Articles published on the blog primary: title history: true properties: title: type: string title: Title options: translate: true slug: type: string title: Slug pattern: ^[a-z0-9-]+$ body: type: richtext title: Body options: translate: true status: type: string title: Status enum: [draft, published] default: draft author: type: relation title: Author bucketId: relationType: onetoone cover: type: storage title: Cover image published_at: type: date title: Published at required: [title, slug] indexes: - definition: {slug: 1} options: {unique: true} - definition: {status: 1, published_at: -1} acl: read: document.status == "published" write: "false == true" ``` `history: true` lets editors restore earlier versions. The unique index keeps slugs unique, and the second index serves the website's main query. ## 2. Give editors access Create a policy for editors: ```yaml title="policy/Content Editor/schema.yaml" name: Content Editor description: Manage posts and authors, upload media statement: - {action: bucket:index, module: bucket, resource: {include: ["*"], exclude: []}} - {action: bucket:show, module: bucket, resource: {include: [, ], exclude: []}} - {action: bucket:data:index, module: bucket:data, resource: {include: [, ], exclude: []}} - {action: bucket:data:show, module: bucket:data, resource: {include: [, ], exclude: []}} - {action: bucket:data:create, module: bucket:data, resource: {include: [, ], exclude: []}} - {action: bucket:data:update, module: bucket:data, resource: {include: [, ], exclude: []}} - {action: bucket:data:delete, module: bucket:data, resource: {include: [, ], exclude: []}} - {action: preference:show, module: preference, resource: {include: [bucket], exclude: []}} ``` Create an [identity](https://docs.spicaengine.com/auth/identities) for each editor and attach `Content Editor` and `StorageFullAccess`. Editors now see only the two buckets in the panel. ## 3. Read published posts on the website The website renders on a server, so it can use an API key. Create a key named `Website` with a read-only policy for the two buckets (`bucket:data:index` and `bucket:data:show`). > **Warning** > > API keys skip bucket rules, so the read rule above doesn't protect drafts from the key. Always filter by `status` in queries made with the key, and keep the key on the server. ```typescript title="lib/blog.ts" import * as Bucket from "@spica-devkit/bucket"; Bucket.initialize({apikey: process.env.SPICA_API_KEY!, publicUrl: process.env.SPICA_URL!}); const POSTS = process.env.POSTS_BUCKET_ID!; export function listPosts(language: string, page = 0) { return Bucket.data.getAll(POSTS, { queryParams: { filter: 'document.status == "published"', sort: {published_at: -1}, limit: 10, skip: page * 10, paginate: true, relation: ["author"] }, headers: {"Accept-Language": language} }); } export async function getPost(slug: string, language: string) { const [post] = await Bucket.data.getAll(POSTS, { queryParams: {filter: `document.status == "published" && document.slug == "${slug}"`, limit: 1, relation: ["author"]}, headers: {"Accept-Language": language} }); return post; } ``` Validate `slug` (for example against `^[a-z0-9-]+$`) before you put it into a filter. ## 4. Rebuild the site on every change Static site hosts give you a "deploy hook" URL. Create a [webhook](https://docs.spicaengine.com/platform/webhooks) per operation type that calls it: ```json { "title": "Rebuild site on post update", "url": "https://api.netlify.com/build_hooks/", "body": "{\"trigger\": \"{{type}} {{documentKey}}\"}", "trigger": {"name": "database", "active": true, "options": {"collection": "bucket_", "type": "UPDATE"}} } ``` Repeat it for `INSERT` and `DELETE`. Check deliveries in the webhook's logs. ## 5. Localize The bucket preferences define the languages. Editors fill in each language in the panel, and the site sends the visitor's language in `Accept-Language`. Spica answers with the matching translation or the default language. ## Result - Editors manage posts and authors in the panel, with history and image uploads. - The site reads only published posts, in the visitor's language, with author details resolved. - Every change triggers a rebuild. --- # User sign-up with email verification > Build a public sign-up endpoint, verify users' email addresses with one-time codes, and enable password reset. Creating users needs an API key, so sign-up runs in a function. In this recipe you build: - `POST /fn-execute/auth/sign-up`: creates a user and returns a session. - `POST /fn-execute/auth/email`: sends a verification code to the user's email. - `POST /fn-execute/auth/email/verify`: confirms the code. - Password reset, which Spica serves directly once it is enabled. ## 1. Configure email Start the API with SMTP settings (see [Mailer & SMS](https://docs.spicaengine.com/platform/mailer-and-sms)): ```bash --mailer-host=smtp.example.com --mailer-port=587 \ --mailer-user=apikey --mailer-pass= \ --mailer-from="Acme " ``` Enable email verification and password reset in the `user` [configuration](https://docs.spicaengine.com/platform/config), together with a password policy: ```bash curl -X PUT https://api.example.com/api/config/user \ -H "Authorization: IDENTITY " -H "Content-Type: application/json" \ -d '{ "password": {"minLength": 8, "minNumber": 1}, "providerVerificationConfig": [{"provider": "email", "strategy": "Otp"}], "resetPasswordProvider": [{"provider": "email", "strategy": "Otp"}], "verificationProcessMaxAttempt": 5, "rateLimits": {"createUser": {"limit": 20, "ttl": 60}, "providerVerification": {"limit": 5, "ttl": 300}} }' ``` ## 2. Create an API key for the function Create an API key named `Auth function` with `UserFullAccess`, and store it as a [secret](https://docs.spicaengine.com/functions/environment) named `SPICA_API_KEY`. ## 3. Write the function ```yaml title="function/auth/schema.yaml" name: auth description: Public sign-up and email verification language: javascript timeout: 20 triggers: signUp: type: http active: true options: method: Post path: /auth/sign-up rateLimit: {limit: 10, ttl: 60000} sendEmailCode: type: http active: true options: method: Post path: /auth/email authenticate: [USER] verifyEmailCode: type: http active: true options: method: Post path: /auth/email/verify authenticate: [USER] secrets: [] ``` ```json title="function/auth/package.json" {"name": "auth", "version": "0.0.1", "dependencies": {"@spica-devkit/auth": "^0.22.1"}} ``` ```javascript title="function/auth/index.mjs" import * as Auth from "@spica-devkit/auth"; Auth.initialize({apikey: process.env.SPICA_API_KEY}); const EMAIL = /^[^@\s]+@[^@\s]+\.[^@\s]+$/; export async function signUp(req, res) { const {email, password} = req.body ?? {}; if (!EMAIL.test(email ?? "") || typeof password != "string" || password.length < 8) { return res.status(400).send({message: "A valid email and a password of at least 8 characters are required."}); } try { const user = await Auth.signUp({username: email, password}); const session = await Auth.signIn(email, password); return res.status(201).send({userId: user._id, token: session.token}); } catch (error) { const status = error?.statusCode ?? error?.status ?? 500; return res.status(status == 400 ? 409 : 500).send({message: "Could not create the account."}); } } async function currentUser(req) { const token = (req.headers.get("authorization") ?? "").replace(/^USER /, ""); return Auth.verifyToken(token); } export async function sendEmailCode(req, res) { const user = await currentUser(req); await Auth.addEmail(user._id, user.username, "Otp"); return {message: "Code sent"}; } export async function verifyEmailCode(req, res) { const user = await currentUser(req); const {code} = req.body ?? {}; try { return await Auth.verifyEmail(user._id, String(code), "Otp"); } catch { return res.status(400).send({message: "Invalid or expired code."}); } } ``` Attaching an email to a user requires `passport:user:update`, which users don't have on themselves. The function checks the caller's token and then acts with its API key. ## 4. Use it from your app ```javascript const API = "https://api.example.com/api"; const {token} = await fetch(`${API}/fn-execute/auth/sign-up`, { method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify({email: "grace@example.com", password: "graceHopper1"}) }).then(r => r.json()); await fetch(`${API}/fn-execute/auth/email`, {method: "POST", headers: {Authorization: `USER ${token}`}}); await fetch(`${API}/fn-execute/auth/email/verify`, { method: "POST", headers: {Authorization: `USER ${token}`, "Content-Type": "application/json"}, body: JSON.stringify({code: "123456"}) }); ``` ```json {"userId": "6b0b529fa5611972c29c2700", "token": "eyJhbGciOiJIUzI1NiIs..."} ``` Signing up twice with the same email returns `409`, and invalid input returns `400`. ## 5. Password reset With `resetPasswordProvider` configured, the app calls Spica directly, without a token: ```javascript await fetch(`${API}/passport/user/forgot-password/start`, { method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify({username: "grace@example.com", provider: "email"}) }); await fetch(`${API}/passport/user/forgot-password/verify`, { method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify({username: "grace@example.com", code: "123456", newPassword: "aNewPassword9", provider: "email"}) }); ``` ## Next steps - Give new users a default policy in `signUp` with `Auth.policy.attach(user._id, [""])`. - Offer [passwordless login](https://docs.spicaengine.com/auth/users#passwordless-login) and [OAuth](https://docs.spicaengine.com/auth/strategies). - Send a [welcome email](https://docs.spicaengine.com/recipes/welcome-email) when users sign up. --- # Welcome email for new users > Send a welcome email whenever a user is created, with a database trigger, nodemailer and secrets. Spica's mailer only sends Passport's verification messages. For your own emails, call your provider from a function. This recipe sends a welcome email every time a user is created, however the user was created. ## 1. Store the SMTP credentials Create these [secrets](https://docs.spicaengine.com/functions/environment): `SMTP_HOST`, `SMTP_USER`, `SMTP_PASS`, and an environment variable `MAIL_FROM`. ## 2. The function ```yaml title="function/welcome-email/schema.yaml" name: welcome-email description: Sends a welcome email to new users language: javascript timeout: 30 triggers: onUserCreated: type: database active: true options: collection: user type: INSERT env_vars: [] secrets: [, , ] ``` ```json title="function/welcome-email/package.json" {"name": "welcome-email", "version": "0.0.1", "dependencies": {"nodemailer": "^6.9.0"}} ``` ```javascript title="function/welcome-email/index.mjs" import nodemailer from "nodemailer"; const transport = nodemailer.createTransport({ host: process.env.SMTP_HOST, port: 587, auth: {user: process.env.SMTP_USER, pass: process.env.SMTP_PASS} }); export async function onUserCreated(change) { const email = change.document?.username; if (!email?.includes("@")) { return; } await transport.sendMail({ from: process.env.MAIL_FROM, to: email, subject: "Welcome to Acme", text: "Thanks for signing up! Reply to this email if you need anything." }); console.info("Welcome email sent", change.documentKey); } ``` The trigger receives the new user document. In this example usernames are email addresses, as in the [sign-up recipe](https://docs.spicaengine.com/recipes/user-signup-verification). ## Why a database trigger? Users live in Spica's `user` collection, not in a bucket, so the [database trigger](https://docs.spicaengine.com/functions/bucket-and-database#database-trigger) is the way to react to them. It fires for users created by your sign-up function, by OAuth logins and by the panel alike. ## Make it robust - **Idempotency.** Record sent emails (for example in a `Sent emails` bucket keyed by user id) and skip users who already got one. - **Failures.** Log errors with `console.error` and the user id, and filter on them in the logs. - **Providers with HTTP APIs.** Replace nodemailer with `fetch` calls to your provider's API, keeping the API key in a secret. --- # Scheduled cleanup job > Delete expired documents every night with a schedule trigger, processing them in batches that fit in a function's timeout. Many apps store short-lived data: sessions, one-time links, carts, notifications. This recipe removes expired documents from a `Sessions` bucket every night. ## 1. The bucket ```yaml title="bucket/Sessions/schema.yaml" title: Sessions description: Temporary sessions primary: token properties: token: type: string title: Token expires_at: type: date title: Expires at indexes: - definition: {expires_at: 1} ``` The index on `expires_at` keeps the cleanup query fast as the bucket grows. ## 2. The function Store an API key with access to the bucket as the secret `SPICA_API_KEY`, and the bucket id as the environment variable `SESSIONS_BUCKET_ID`. ```yaml title="function/cleanup/schema.yaml" name: cleanup description: Removes expired sessions language: javascript timeout: 60 triggers: removeExpiredSessions: type: schedule active: true options: frequency: "0 3 * * *" timezone: UTC env_vars: [] secrets: [] ``` ```javascript title="function/cleanup/index.mjs" import * as Bucket from "@spica-devkit/bucket"; Bucket.initialize({apikey: process.env.SPICA_API_KEY}); const BATCH_SIZE = 100; export async function removeExpiredSessions() { const bucketId = process.env.SESSIONS_BUCKET_ID; const filter = "unixTime(document.expires_at) < now()"; let removed = 0; while (true) { const expired = await Bucket.data.getAll(bucketId, {queryParams: {filter, limit: BATCH_SIZE}}); if (!expired.length) { break; } await Bucket.data.removeMany(bucketId, expired.map(session => session._id)); removed += expired.length; } console.info(`Removed ${removed} expired sessions`); return removed; } ``` Each iteration reads one page of expired sessions and deletes it with a single [batch request](https://docs.spicaengine.com/platform/batch), until nothing is left. ## 3. Run it on demand While you develop, add an HTTP trigger that calls the same code, and remove it before going to production: ```javascript export async function runNow() { return {removed: await removeExpiredSessions()}; } ``` ```yaml runNow: type: http active: true options: method: Post path: /cleanup/run authenticate: [IDENTITY] ``` ```json {"removed": 7} ``` ## Variations - **Very large backlogs.** Stop after a number of batches and let the next run continue, so one run never hits the timeout. - **Keep only the latest N documents.** Use [document limits](https://docs.spicaengine.com/buckets/advanced#document-limits) with `limitExceedBehaviour: remove` instead of a job. - **Archive instead of delete.** Insert the documents into an archive bucket or object storage before removing them. --- # CI/CD with GitHub Actions > Review Spica changes as plans on pull requests and apply them to staging and production when they merge, with GitHub Actions and the Spica CLI. Keep your project's resources in the repository (see [Resources as code](https://docs.spicaengine.com/cli/resources-as-code)) and let CI deploy them: - On pull requests, `spica plan` shows what would change. - On merge to `main`, `spica apply` updates staging, then production after approval. ## Repository layout ```text . ├── spica/ │ ├── bucket/ │ ├── function/ │ ├── policy/ │ ├── env-var/ │ └── secret/ └── .github/workflows/spica.yml ``` ## Secrets and variables | GitHub setting | Value | | ------------------------------------------------------------------- | ------------------------------------------------------------- | | Environment `staging`: secret `SPICA_API_KEY`, variable `SPICA_URL` | An API key for the CLI and the staging API URL. | | Environment `production`: same names | Production values. Add required reviewers to the environment. | | Secrets such as `STRIPE_KEY` per environment | Exposed to the CLI as `SPICA_VALUE_`. | The API keys need the full-access policies of the modules you manage: buckets, functions, policies, environment variables and secrets. ## Workflow ````yaml title=".github/workflows/spica.yml" name: Spica on: pull_request: paths: ["spica/**"] push: branches: [main] paths: ["spica/**"] jobs: plan: if: github.event_name == 'pull_request' runs-on: ubuntu-latest environment: staging steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 22 - run: npm install -g @spica/cli@0.22.1 - name: Connect run: | spica context set --name ci --url "${{ vars.SPICA_URL }}" --apikey "${{ secrets.SPICA_API_KEY }}" spica context switch ci - name: Plan working-directory: spica env: SPICA_VALUE_STRIPE_KEY: ${{ secrets.STRIPE_KEY }} run: | set +e spica plan --detailed --detailed-exitcode > plan.txt code=$? sed -i 's/\x1b\[[0-9;]*m//g' plan.txt set -e { echo '```diff'; cat plan.txt; echo '```'; } >> "$GITHUB_STEP_SUMMARY" if [ "$code" -ne 0 ] && [ "$code" -ne 2 ]; then exit "$code"; fi deploy: if: github.event_name == 'push' runs-on: ubuntu-latest strategy: max-parallel: 1 matrix: environment: [staging, production] environment: ${{ matrix.environment }} steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 22 - run: npm install -g @spica/cli@0.22.1 - name: Connect run: | spica context set --name ci --url "${{ vars.SPICA_URL }}" --apikey "${{ secrets.SPICA_API_KEY }}" spica context switch ci - name: Apply working-directory: spica env: SPICA_VALUE_STRIPE_KEY: ${{ secrets.STRIPE_KEY }} run: spica apply --auto-approve --abort-on-error ```` `spica plan --detailed-exitcode` exits with `2` when there are changes. The plan step above accepts `0` and `2` and fails on real errors, removes terminal color codes, and writes the plan to the job summary for reviewers. ## Practices that keep deployments safe - **Review deletions.** A resource missing from the folder is deleted on apply, together with a bucket's documents. Treat `-` lines in the plan as red flags. - **Pin versions.** Use the same CLI version as your instances. - **Protect production.** Require reviewers on the `production` environment, so `apply` waits for approval after staging succeeded. - **One source of truth.** Don't edit managed resources in the production panel. Changes made there are overwritten by the next apply, or show up in the next plan. - **Values outside git.** Pass secret values through `SPICA_VALUE_*` variables and never commit `.spica/`. For full control, for example to approve plans in your own tool before applying them, use [`@spica-devkit/sync`](https://docs.spicaengine.com/devkit/sync), which plans from a repository archive and applies only the plan that was approved. --- # End-to-end tests > Test your buckets, rules and functions against a disposable Spica instance with @spica-devkit/testing and Vitest. [`@spica-devkit/testing`](https://docs.spicaengine.com/devkit/testing) starts a real Spica API with your project's resources installed. Your tests then call it exactly like your apps do, which makes it the best way to test rules, policies and functions together. ## Setup ```bash npm install --save-dev vitest @spica-devkit/testing @spica-devkit/bucket @spica-devkit/auth ``` The project folder contains your [resource files](https://docs.spicaengine.com/cli/resources-as-code), for example `spica/bucket/Posts/schema.yaml` and `spica/function/auth/`. ```typescript title="vitest.config.ts" import {defineConfig} from "vitest/config"; export default defineConfig({ test: { hookTimeout: 180_000, testTimeout: 30_000, fileParallelism: false } }); ``` ## A test file ```typescript title="test/posts.e2e.test.ts" import * as Auth from "@spica-devkit/auth"; import * as Bucket from "@spica-devkit/bucket"; import {start} from "@spica-devkit/testing"; import {afterAll, afterEach, beforeAll, expect, test} from "vitest"; let spica: Awaited>; let postsBucketId: string; beforeAll(async () => { spica = await start({version: "0.22.1", resourcePath: "./spica"}); const {token} = await fetch(`${spica.publicUrl}/passport/identify`, { method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify({identifier: "spica", password: "spica"}) }).then(r => r.json()); Bucket.initialize({identity: token, publicUrl: spica.publicUrl}); Auth.initialize({identity: token, publicUrl: spica.publicUrl}); const buckets = await Bucket.getAll(); postsBucketId = buckets.find(bucket => bucket.title == "Posts")!._id; }); afterEach(() => spica.reset(["bucket-data"])); afterAll(() => spica.teardown()); test("users only see published posts", async () => { await Bucket.data.insert(postsBucketId, {title: {en_US: "Draft"}, slug: "draft", status: "draft"}); await Bucket.data.insert(postsBucketId, {title: {en_US: "Live"}, slug: "live", status: "published"}); const reader = await Auth.signUp({username: "reader@example.com", password: "readerPass1"}); await Auth.policy.attach(reader._id, ["BucketReadOnlyAccess"]); const session = await Auth.signIn("reader@example.com", "readerPass1"); const response = await fetch(`${spica.publicUrl}/bucket/${postsBucketId}/data`, { headers: {Authorization: `USER ${session.token}`} }); const posts = await response.json(); expect(posts.map(post => post.slug)).toEqual(["live"]); }); test("slugs are validated", async () => { await expect( Bucket.data.insert(postsBucketId, {title: {en_US: "Bad"}, slug: "Not A Slug"}) ).rejects.toBeTruthy(); }); ``` `publicUrl` has no `/api` suffix: the testing instance serves the API directly. ## Testing functions HTTP functions are served at `${spica.publicUrl}/fn-execute/`: ```typescript test("sign-up returns a token", async () => { const response = await fetch(`${spica.publicUrl}/fn-execute/auth/sign-up`, { method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify({email: "new@example.com", password: "newUserPass1"}) }); expect(response.status).toBe(201); expect((await response.json()).token).toBeTypeOf("string"); }); ``` Install only the resources a test file needs to make boots faster: ```typescript spica = await start({resourcePath: "./spica", installResources: {bucket: ["Posts"], function: ["auth"]}}); ``` ## In CI GitHub's `ubuntu-latest` runners include Docker: ```yaml - uses: actions/setup-node@v4 with: node-version: 22 - run: npm ci - run: npx vitest run test/*.e2e.test.ts ``` ## Tips - Use `reset(["bucket-data"])` between tests and a fresh instance per test file. - Run test files one at a time (`fileParallelism: false`) unless each file starts its own instance on purpose. - Test as a **user** when you test rules. Identities and API keys bypass them. --- # User uploads on Amazon S3 > Store files on Amazon S3 and let signed-in users upload avatars through an HTTP function that checks their token. Storage endpoints accept identities and API keys, not users. To let end users upload files, accept the upload in a function that checks the user's token and stores the file with an API key. This recipe stores avatars on S3 and saves their URL in a `Profiles` bucket. ## 1. Store files on S3 Start the API with the S3 strategy: ```bash --storage-strategy=awss3 \ --awss3-bucket-name=acme-spica-media ``` Credentials come from the AWS default credential chain (environment variables, an EKS service account role or an instance profile), or from a JSON file passed with `--awss3-credentials-path`. The identity needs `s3:PutObject`, `s3:GetObject` and `s3:DeleteObject` on the bucket. Object URLs then point to S3 directly, for example `https://acme-spica-media.s3.eu-central-1.amazonaws.com/avatars/-1795889886000.png`. To serve avatars publicly, allow public reads on the `avatars/` prefix with a bucket policy, or put CloudFront in front of the bucket. ## 2. The profile bucket ```yaml title="bucket/Profiles/schema.yaml" title: Profiles description: Public profile of each user primary: name properties: user: type: string title: User id name: type: string title: Name avatar: type: storage title: Avatar indexes: - definition: {user: 1} options: {unique: true} ``` ## 3. The upload function Store an API key with `StorageFullAccess` and data access to `Profiles` as the secret `SPICA_API_KEY`, and the bucket id as `PROFILES_BUCKET_ID`. ```yaml title="function/avatar/schema.yaml" name: avatar description: Uploads the caller's avatar language: javascript timeout: 30 triggers: upload: type: http active: true options: method: Post path: /me/avatar authenticate: [USER] rateLimit: {limit: 10, ttl: 60000} ``` ```javascript title="function/avatar/index.mjs" import * as Auth from "@spica-devkit/auth"; import * as Bucket from "@spica-devkit/bucket"; import * as Storage from "@spica-devkit/storage"; Auth.initialize({apikey: process.env.SPICA_API_KEY}); Bucket.initialize({apikey: process.env.SPICA_API_KEY}); Storage.initialize({apikey: process.env.SPICA_API_KEY}); const TYPES = {"image/png": "png", "image/jpeg": "jpg", "image/webp": "webp"}; const MAX_BYTES = 2 * 1024 * 1024; export async function upload(req, res) { const token = (req.headers.get("authorization") ?? "").replace(/^USER /, ""); const user = await Auth.verifyToken(token); const {contentType, data} = req.body ?? {}; const extension = TYPES[contentType]; const content = data ? Buffer.from(data, "base64") : undefined; if (!extension || !content || content.length > MAX_BYTES) { return res.status(400).send({message: "Send a PNG, JPEG or WebP image up to 2 MB as base64."}); } const object = await Storage.insert({ name: `avatars/${user._id}-${Date.now()}.${extension}`, contentType, data: content }); const [profile] = await Bucket.data.getAll(process.env.PROFILES_BUCKET_ID, { queryParams: {filter: `document.user == "${user._id}"`, limit: 1} }); if (profile) { await Bucket.data.patch(process.env.PROFILES_BUCKET_ID, profile._id, {avatar: object.url}); } else { await Bucket.data.insert(process.env.PROFILES_BUCKET_ID, {user: user._id, name: user.username, avatar: object.url}); } return {url: object.url}; } ``` Install `@spica-devkit/auth`, `@spica-devkit/bucket` and `@spica-devkit/storage` as [dependencies](https://docs.spicaengine.com/functions/dependencies) of the function. ## 4. Upload from the app ```javascript async function uploadAvatar(file, token) { const data = btoa(String.fromCharCode(...new Uint8Array(await file.arrayBuffer()))); const response = await fetch("https://api.example.com/api/fn-execute/me/avatar", { method: "POST", headers: {Authorization: `USER ${token}`, "Content-Type": "application/json"}, body: JSON.stringify({contentType: file.type, data}) }); return (await response.json()).url; } ``` ## Notes - Request bodies are limited by `--payload-size-limit` (15 MiB by default), and base64 adds about a third to the size. For large files, use [resumable uploads](https://docs.spicaengine.com/storage#resumable-uploads) from a trusted backend instead. - Validate the content type and size in the function. The storage API accepts any file. - Object names are unique: inserting an existing name fails with `An object with this name already exists.` The function adds a timestamp to every upload, which also busts caches. Delete the previous avatar with `Storage.remove` if you don't want to keep it.