# `npx @sanity/cli functions add`

Scaffold a local Function and its resource definition for the current Blueprint.

## Before running

- Run from a project containing a Blueprint manifest.
- Choose a Function name not already used by a Blueprint resource, and one event family: document, media-library asset, scheduled, or sync-tag invalidation.
- Names must be at least three characters, start with a letter or digit, and otherwise contain only letters, digits, hyphens, and underscores.
- Decide whether to install `@sanity/functions`, which provides typed helpers for authoring handler code, and which package manager to use.

## Add a Function

Provide flags to avoid interactive prompts:

```sh
npx @sanity/cli functions add --name process-order --type document-create --type document-update --language ts --helpers --installer npm
```

No flag is required and any omitted value is prompted for, but `--type` without `--name` is rejected. The accepted `--type` values are `document-create`, `document-update`, `document-delete`, `document-publish`, `media-library-asset-create`, `media-library-asset-update`, `media-library-asset-delete`, `scheduled-function`, and `sync-tag-invalidate`. Repeat the flag for multiple events from the same family; the command rejects a mix of families.

TypeScript is the default language. Use `--language js` or `--javascript` for JavaScript, but do not combine those flags. Use `--no-helpers` when helper installation is not wanted. `--installer` accepts `npm`, `pnpm`, `yarn`, or `skip`.

`--example EXAMPLE_NAME` downloads a Function example from the `sanity-labs/function-recipes` repository into `functions/EXAMPLE_NAME/` instead of running the normal scaffold flow. Browse recipes at https://www.sanity.io/exchange/type=recipes/solution=functions. Each recipe's Quick Start contains the correct `--example` value. Pass it alone: every other scaffold flag is rejected, and the manifest is not updated. Use it only for an example the user requested, then follow the configuration instructions printed by the command.

## Verify

The scaffold writes one file, `functions/NAME/index.ts` (or `index.js`). Only `.json` manifests are edited in place; for `.ts`, `.js`, and `.mjs` manifests the command prints a resource definition that still needs to be added by hand.

Run the Function locally with a payload that matches the handler before deployment:

```sh
npx @sanity/cli functions test process-order --file payload.json --json
npx @sanity/cli blueprints plan --json
```
