From f756acc561d3d6f7cbc6208923d4a3c73e27da65 Mon Sep 17 00:00:00 2001 From: yomna Date: Mon, 9 Feb 2026 23:10:25 -0500 Subject: [PATCH 1/9] [Workers] Add Builds API guide with workflow examples MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Document required permissions (Workers Builds Configuration + Workers Scripts Read) - Explain Worker tag vs Worker name (external_script_id) distinction - Add complete workflow: get Worker tag → get trigger UUID → work with builds - Include production vs preview trigger setup with environment variables - Add redeploy script example for refreshing build-time data - Add end-to-end setup example from GitHub repo connection to first build - Add troubleshooting section for common errors --- .../workers/ci-cd/builds/api-reference.mdx | 510 ++++++++++++++++++ 1 file changed, 510 insertions(+) create mode 100644 src/content/docs/workers/ci-cd/builds/api-reference.mdx diff --git a/src/content/docs/workers/ci-cd/builds/api-reference.mdx b/src/content/docs/workers/ci-cd/builds/api-reference.mdx new file mode 100644 index 00000000000..df71faefc18 --- /dev/null +++ b/src/content/docs/workers/ci-cd/builds/api-reference.mdx @@ -0,0 +1,510 @@ +--- +pcx_content_type: how-to +title: Use the Builds API +description: Learn how to programmatically trigger builds, manage triggers, and monitor your Workers Builds using the API. +sidebar: + order: 11 +--- + +This guide walks you through using the Workers Builds API to programmatically manage your builds. Before diving into specific endpoints, this guide covers two important concepts that will help you get started faster. + +## Before you start + +### 1. Create an API token with the correct permissions + +The Builds API requires a user-scoped API token with specific permissions. Create your token at [dash.cloudflare.com/profile/api-tokens](https://dash.cloudflare.com/profile/api-tokens). + +**Required permissions:** + +| Permission | Access | Why you need it | +|------------|--------|-----------------| +| Workers Builds Configuration | Edit | Trigger builds, update triggers, manage environment variables | +| Workers Scripts | Read | Retrieve Worker tags (required for all Builds API calls) | + +:::caution[Common mistake] +If you only add the **Workers Builds Configuration** permission, you will not be able to retrieve Worker tags. You need **both** permissions. +::: + +### 2. Worker tags vs Worker names + +The Builds API uses a **Worker tag** to identify Workers. In the API, this is called `external_script_id` — this is the same as the Worker tag, just with a different name. + +| Identifier | Example | Where it comes from | +|------------|---------|---------------------| +| Worker name (`id`) | `my-worker` | The name you gave your Worker | +| Worker tag (`external_script_id`) | `1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d` | Immutable UUID assigned by Cloudflare | + +Every Builds API endpoint that references a Worker requires the **tag**, not the name. This is not documented clearly in the REST API reference. + +## Complete workflow + +Here is the typical workflow for interacting with the Builds API: + +```txt +┌─────────────────────────────────────────────────────────────────┐ +│ 1. Get Worker tag (from Workers Scripts API) │ +│ GET /workers/scripts → find your Worker → note the "tag" │ +└─────────────────────────────────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────────────┐ +│ 2. Get trigger UUID (using the Worker tag) │ +│ GET /builds/workers/{tag}/triggers → note "trigger_uuid" │ +└─────────────────────────────────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────────────┐ +│ 3. Do things with builds │ +│ - Trigger a build: POST /builds/triggers/{trigger_uuid}/... │ +│ - List builds: GET /builds/workers/{tag}/builds │ +│ - Get logs: GET /builds/builds/{build_uuid}/logs │ +└─────────────────────────────────────────────────────────────────┘ +``` + +## Step 1: Get your Worker tag + +Call the Workers Scripts API to list all your Workers and find the `tag` for the Worker you want to work with: + +```bash +curl -s "https://api.cloudflare.com/client/v4/accounts/{account_id}/workers/scripts" \ + --header "Authorization: Bearer " \ + | jq '.result[] | {name: .id, tag: .tag}' +``` + +Example output: + +```json +{ + "name": "my-worker", + "tag": "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d" +} +{ + "name": "another-worker", + "tag": "8a1b2c3d4e5f67890abcdef123456789" +} +``` + +Save the `tag` value for your Worker. You will use it in all subsequent API calls. + +## Step 2: Get your trigger UUID + +Each Worker can have a maximum of two triggers: + +| Trigger type | Purpose | Typical branch pattern | +|--------------|---------|------------------------| +| **Production** | Deploys to your live Worker | `main` or `master` | +| **Preview** | Creates preview deployments for testing | `*` (all branches except production) | + +:::note +The two-trigger limit is enforced by the API. If you attempt to create a third trigger, the request will fail. +::: + +Each trigger has its own configuration, including separate build commands, deploy commands, and environment variables. This allows you to have different settings for production and preview builds (for example, different `NODE_ENV` values or API keys). + +Use the Worker tag to list triggers: + +```bash +curl -s "https://api.cloudflare.com/client/v4/accounts/{account_id}/builds/workers/{worker_tag}/triggers" \ + --header "Authorization: Bearer " \ + | jq '.result[] | {trigger_uuid, trigger_name, branch_includes, branch_excludes}' +``` + +Example output: + +```json +{ + "trigger_uuid": "f47ac10b-58cc-4372-a567-0e02b2c3d479", + "trigger_name": "Deploy production", + "branch_includes": ["main"], + "branch_excludes": [] +} +{ + "trigger_uuid": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", + "trigger_name": "Deploy non-production branches", + "branch_includes": ["*"], + "branch_excludes": ["main"] +} +``` + +Save the `trigger_uuid` for the trigger you want to work with. Remember, you will have at most two triggers: one for your production branch (for example, `main`) that deploys to your live Worker, and optionally one for all other branches that creates preview deployments. + +## Step 3: Work with builds + +Now that you have the Worker tag and trigger UUID, you can trigger builds, list build history, and get logs. + +### Trigger a manual build + +Use the `trigger_uuid` from [Step 2](#step-2-get-your-trigger-uuid). + +```bash +curl -s "https://api.cloudflare.com/client/v4/accounts/{account_id}/builds/triggers/{trigger_uuid}/builds" \ + --header "Authorization: Bearer " \ + --header "Content-Type: application/json" \ + --request POST \ + --data '{"branch": "main"}' +``` + +You can specify either `branch` or `commit_hash`: + +| Field | Description | +|-------|-------------| +| `branch` | Git branch name to build (for example, `main`) | +| `commit_hash` | Specific commit SHA to build | + +The response includes the `build_uuid` which you can use to monitor the build. + +### List builds for a Worker + +Use the `worker_tag` from [Step 1](#step-1-get-your-worker-tag). + +```bash +curl -s "https://api.cloudflare.com/client/v4/accounts/{account_id}/builds/workers/{worker_tag}/builds" \ + --header "Authorization: Bearer " \ + | jq '.result[] | {build_uuid, status, branch, created_at}' +``` + +The response includes `build_uuid` for each build, which you need for getting logs or canceling builds. + +### Get build logs + +Use the `build_uuid` from [List builds](#list-builds-for-a-worker) or from the response when triggering a build. + +```bash +curl -s "https://api.cloudflare.com/client/v4/accounts/{account_id}/builds/builds/{build_uuid}/logs" \ + --header "Authorization: Bearer " +``` + +### Cancel a running build + +Use the `build_uuid` from [List builds](#list-builds-for-a-worker) or from the response when triggering a build. + +```bash +curl -s "https://api.cloudflare.com/client/v4/accounts/{account_id}/builds/builds/{build_uuid}/cancel" \ + --header "Authorization: Bearer " \ + --request PUT +``` + +## Update trigger configuration + +Use the `trigger_uuid` from [Step 2](#step-2-get-your-trigger-uuid). + +```bash +curl -s "https://api.cloudflare.com/client/v4/accounts/{account_id}/builds/triggers/{trigger_uuid}" \ + --header "Authorization: Bearer " \ + --header "Content-Type: application/json" \ + --request PATCH \ + --data '{ + "build_command": "npm run build:prod", + "deploy_command": "npx wrangler deploy" + }' +``` + +**Editable fields:** + +| Field | Type | Description | +|-------|------|-------------| +| `trigger_name` | string | Display name for the trigger | +| `build_command` | string | Command to build your project | +| `deploy_command` | string | Command to deploy your Worker | +| `root_directory` | string | Path to your project root | +| `branch_includes` | array | Branch patterns to trigger builds | +| `branch_excludes` | array | Branch patterns to exclude | +| `path_includes` | array | File path patterns that trigger builds | +| `path_excludes` | array | File path patterns to ignore | +| `build_caching_enabled` | boolean | Turn on or off build caching | + +## Manage build environment variables + +Environment variables are set per trigger, meaning you can have different values for production and preview builds. For example, you might set `NODE_ENV=production` on your production trigger and `NODE_ENV=development` on your preview trigger. + +:::note +These are **build-time** environment variables, available only during the build process. For runtime environment variables, refer to [Environment variables](/workers/configuration/environment-variables/). +::: + +### List environment variables + +Use the `trigger_uuid` from [Step 2](#step-2-get-your-trigger-uuid). + +```bash +curl -s "https://api.cloudflare.com/client/v4/accounts/{account_id}/builds/triggers/{trigger_uuid}/environment_variables" \ + --header "Authorization: Bearer " +``` + +### Set environment variables + +You can set different variables for each trigger. For example, to set production environment variables: + +```bash +curl -s "https://api.cloudflare.com/client/v4/accounts/{account_id}/builds/triggers/{production_trigger_uuid}/environment_variables" \ + --header "Authorization: Bearer " \ + --header "Content-Type: application/json" \ + --request PATCH \ + --data '{ + "variables": [ + {"key": "NODE_ENV", "value": "production", "type": "text"}, + {"key": "API_KEY", "value": "prod-secret-key", "type": "secret"} + ] + }' +``` + +And different values for preview builds: + +```bash +curl -s "https://api.cloudflare.com/client/v4/accounts/{account_id}/builds/triggers/{preview_trigger_uuid}/environment_variables" \ + --header "Authorization: Bearer " \ + --header "Content-Type: application/json" \ + --request PATCH \ + --data '{ + "variables": [ + {"key": "NODE_ENV", "value": "development", "type": "text"}, + {"key": "API_KEY", "value": "dev-secret-key", "type": "secret"} + ] + }' +``` + +Use `type: "text"` for plain values and `type: "secret"` for sensitive values that should be masked in logs. + +### Delete an environment variable + +Use the `trigger_uuid` from [Step 2](#step-2-get-your-trigger-uuid). The `variable_key` is the key name you set (for example, `NODE_ENV`). + +```bash +curl -s "https://api.cloudflare.com/client/v4/accounts/{account_id}/builds/triggers/{trigger_uuid}/environment_variables/{variable_key}" \ + --header "Authorization: Bearer " \ + --request DELETE +``` + +## Purge build cache + +Use the `trigger_uuid` from [Step 2](#step-2-get-your-trigger-uuid). This clears cached dependencies and build artifacts for that trigger. + +```bash +curl -s "https://api.cloudflare.com/client/v4/accounts/{account_id}/builds/triggers/{trigger_uuid}/purge_build_cache" \ + --header "Authorization: Bearer " \ + --request POST +``` + +## Example: Redeploy script + +A common use case is creating a script that redeploys your current active deployment to refresh build-time data. This script demonstrates chaining multiple API calls together: + +```js +import process from "node:process"; +import { ofetch } from "ofetch"; + +async function redeploy() { + const accountId = ""; + const workerName = ""; + + // Step 1: Get the active deployment's version ID + const deployments = await ofetch( + `https://api.cloudflare.com/client/v4/accounts/${accountId}/workers/scripts/${workerName}/deployments`, + { + headers: { Authorization: `Bearer ${process.env.CF_API_TOKEN}` }, + } + ); + const versionId = deployments.result.deployments[0].versions[0].version_id; + + // Step 2: Get the build that created this version + const buildsByVersion = await ofetch( + `https://api.cloudflare.com/client/v4/accounts/${accountId}/builds/builds?version_ids=${versionId}`, + { + headers: { Authorization: `Bearer ${process.env.CF_API_TOKEN}` }, + } + ); + const build = buildsByVersion.result.builds[versionId]; + + // Step 3: Retrigger using the same trigger, branch, and commit + await ofetch( + `https://api.cloudflare.com/client/v4/accounts/${accountId}/builds/triggers/${build.trigger.trigger_uuid}/builds`, + { + method: "POST", + headers: { + Authorization: `Bearer ${process.env.CF_API_TOKEN}`, + "Content-Type": "application/json", + }, + body: JSON.stringify({ + branch: build.build_trigger_metadata.branch, + commit_hash: build.build_trigger_metadata.commit_hash, + }), + } + ); + + console.log("Redeploy triggered successfully"); +} + +redeploy(); +``` + +This script: +1. Gets the currently deployed version from the Workers deployments API +2. Finds the build that created that version using `version_ids` query parameter +3. Triggers a new build with the same branch and commit + +## Example: Set up Workers Builds from scratch + +This example walks through the complete process of connecting a GitHub repository to a Worker and setting up automated builds using only the API. + +### Prerequisites + +Before using the API, you must first install the Cloudflare GitHub App through the dashboard: + +1. Go to **Workers & Pages** in the [Cloudflare dashboard](https://dash.cloudflare.com). +2. Select any Worker and go to **Settings** > **Builds** > **Connect**. +3. Select **GitHub** and authorize the Cloudflare GitHub App for your account or organization. + +This one-time setup creates the connection between your GitHub account and Cloudflare. Once complete, you can use the API for everything else. + +### Step 1: Get your GitHub account information + +After installing the GitHub App, you need your GitHub account ID and repository ID. You can find these from an existing trigger or from the GitHub API. + +From GitHub's API: + +```bash +# Get your GitHub user/org ID +curl -s "https://api.github.com/users/" | jq '.id' + +# Get a repository ID +curl -s "https://api.github.com/repos//" | jq '.id' +``` + +### Step 2: Create a repository connection + +Create a connection between your GitHub repository and Cloudflare: + +```bash +curl -s "https://api.cloudflare.com/client/v4/accounts/{account_id}/builds/repos/connections" \ + --header "Authorization: Bearer " \ + --header "Content-Type: application/json" \ + --request PUT \ + --data '{ + "provider_type": "github", + "provider_account_id": "", + "provider_account_name": "", + "repo_id": "", + "repo_name": "" + }' +``` + +Save the `repo_connection_uuid` from the response. + +### Step 3: Get your Worker tag + +```bash +curl -s "https://api.cloudflare.com/client/v4/accounts/{account_id}/workers/scripts" \ + --header "Authorization: Bearer " \ + | jq '.result[] | {name: .id, tag: .tag}' +``` + +### Step 4: Create a production trigger + +Create a trigger that deploys when you push to `main`: + +```bash +curl -s "https://api.cloudflare.com/client/v4/accounts/{account_id}/builds/triggers" \ + --header "Authorization: Bearer " \ + --header "Content-Type: application/json" \ + --request POST \ + --data '{ + "external_script_id": "", + "repo_connection_uuid": "", + "trigger_name": "Deploy production", + "build_command": "npm run build", + "deploy_command": "npx wrangler deploy", + "root_directory": "/", + "branch_includes": ["main"], + "branch_excludes": [], + "path_includes": ["*"], + "path_excludes": [] + }' +``` + +### Step 5: Create a preview trigger (optional) + +Create a second trigger for preview deployments on all other branches: + +```bash +curl -s "https://api.cloudflare.com/client/v4/accounts/{account_id}/builds/triggers" \ + --header "Authorization: Bearer " \ + --header "Content-Type: application/json" \ + --request POST \ + --data '{ + "external_script_id": "", + "repo_connection_uuid": "", + "trigger_name": "Deploy preview branches", + "build_command": "npm run build", + "deploy_command": "npx wrangler versions upload", + "root_directory": "/", + "branch_includes": ["*"], + "branch_excludes": ["main"], + "path_includes": ["*"], + "path_excludes": [] + }' +``` + +Note the different `deploy_command`: production uses `wrangler deploy` while preview uses `wrangler versions upload` to create preview URLs without affecting the live deployment. + +### Step 6: Set environment variables for each trigger + +Set production environment variables: + +```bash +curl -s "https://api.cloudflare.com/client/v4/accounts/{account_id}/builds/triggers/{production_trigger_uuid}/environment_variables" \ + --header "Authorization: Bearer " \ + --header "Content-Type: application/json" \ + --request PATCH \ + --data '{ + "variables": [ + {"key": "NODE_ENV", "value": "production", "type": "text"} + ] + }' +``` + +Set preview environment variables: + +```bash +curl -s "https://api.cloudflare.com/client/v4/accounts/{account_id}/builds/triggers/{preview_trigger_uuid}/environment_variables" \ + --header "Authorization: Bearer " \ + --header "Content-Type: application/json" \ + --request PATCH \ + --data '{ + "variables": [ + {"key": "NODE_ENV", "value": "development", "type": "text"} + ] + }' +``` + +### Step 7: Trigger your first build + +```bash +curl -s "https://api.cloudflare.com/client/v4/accounts/{account_id}/builds/triggers/{production_trigger_uuid}/builds" \ + --header "Authorization: Bearer " \ + --header "Content-Type: application/json" \ + --request POST \ + --data '{"branch": "main"}' +``` + +Your Worker is now connected to GitHub. Future pushes to `main` will automatically trigger production deployments, and pushes to other branches will create preview deployments. + +## Troubleshooting + +### "Authentication error" when calling Builds API + +Your token is missing the **Workers Builds Configuration** permission. Create a new token with the correct permissions. + +### Cannot find Worker tag + +Your token is missing the **Workers Scripts (Read)** permission. The Worker tag comes from a different API (`/workers/scripts`), not the Builds API. + +### "Resource not found" error + +You are likely using the Worker name instead of the Worker tag. The Builds API requires the `tag` (a UUID like `1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d`), not the Worker name. + +## Related resources + +- [Workers Builds REST API reference](/api/resources/workers_builds/) - Complete endpoint documentation +- [Workers Scripts REST API reference](/api/resources/workers/subresources/scripts/) - For retrieving Worker tags +- [Workers Builds overview](/workers/ci-cd/builds/) - Dashboard setup and configuration +- [Build configuration](/workers/ci-cd/builds/configuration/) - Build settings and options +- [Create API token](/fundamentals/api/get-started/create-token/) - How to create tokens with the correct permissions From f9232107a5daff5f06b55f2aa1359b582209aa66 Mon Sep 17 00:00:00 2001 From: yomna Date: Mon, 9 Feb 2026 23:18:47 -0500 Subject: [PATCH 2/9] [Workers] Address bonk review feedback - Remove editorial tone about API docs (line 37) - Simplify troubleshooting section, link to dedicated troubleshoot page - Replace ofetch with built-in fetch in redeploy example --- .../workers/ci-cd/builds/api-reference.mdx | 32 ++++++++----------- 1 file changed, 13 insertions(+), 19 deletions(-) diff --git a/src/content/docs/workers/ci-cd/builds/api-reference.mdx b/src/content/docs/workers/ci-cd/builds/api-reference.mdx index df71faefc18..c9f25f713d1 100644 --- a/src/content/docs/workers/ci-cd/builds/api-reference.mdx +++ b/src/content/docs/workers/ci-cd/builds/api-reference.mdx @@ -34,7 +34,7 @@ The Builds API uses a **Worker tag** to identify Workers. In the API, this is ca | Worker name (`id`) | `my-worker` | The name you gave your Worker | | Worker tag (`external_script_id`) | `1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d` | Immutable UUID assigned by Cloudflare | -Every Builds API endpoint that references a Worker requires the **tag**, not the name. This is not documented clearly in the REST API reference. +Every Builds API endpoint that references a Worker requires the **tag**, not the name. ## Complete workflow @@ -289,38 +289,38 @@ curl -s "https://api.cloudflare.com/client/v4/accounts/{account_id}/builds/trigg A common use case is creating a script that redeploys your current active deployment to refresh build-time data. This script demonstrates chaining multiple API calls together: ```js -import process from "node:process"; -import { ofetch } from "ofetch"; - async function redeploy() { const accountId = ""; const workerName = ""; + const apiToken = process.env.CF_API_TOKEN; // Step 1: Get the active deployment's version ID - const deployments = await ofetch( + const deploymentsResponse = await fetch( `https://api.cloudflare.com/client/v4/accounts/${accountId}/workers/scripts/${workerName}/deployments`, { - headers: { Authorization: `Bearer ${process.env.CF_API_TOKEN}` }, + headers: { Authorization: `Bearer ${apiToken}` }, } ); + const deployments = await deploymentsResponse.json(); const versionId = deployments.result.deployments[0].versions[0].version_id; // Step 2: Get the build that created this version - const buildsByVersion = await ofetch( + const buildsResponse = await fetch( `https://api.cloudflare.com/client/v4/accounts/${accountId}/builds/builds?version_ids=${versionId}`, { - headers: { Authorization: `Bearer ${process.env.CF_API_TOKEN}` }, + headers: { Authorization: `Bearer ${apiToken}` }, } ); + const buildsByVersion = await buildsResponse.json(); const build = buildsByVersion.result.builds[versionId]; // Step 3: Retrigger using the same trigger, branch, and commit - await ofetch( + await fetch( `https://api.cloudflare.com/client/v4/accounts/${accountId}/builds/triggers/${build.trigger.trigger_uuid}/builds`, { method: "POST", headers: { - Authorization: `Bearer ${process.env.CF_API_TOKEN}`, + Authorization: `Bearer ${apiToken}`, "Content-Type": "application/json", }, body: JSON.stringify({ @@ -489,17 +489,11 @@ Your Worker is now connected to GitHub. Future pushes to `main` will automatical ## Troubleshooting -### "Authentication error" when calling Builds API - -Your token is missing the **Workers Builds Configuration** permission. Create a new token with the correct permissions. - -### Cannot find Worker tag - -Your token is missing the **Workers Scripts (Read)** permission. The Worker tag comes from a different API (`/workers/scripts`), not the Builds API. - ### "Resource not found" error -You are likely using the Worker name instead of the Worker tag. The Builds API requires the `tag` (a UUID like `1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d`), not the Worker name. +You are likely using the Worker name instead of the Worker tag. The Builds API requires the `tag` (a UUID like `1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d`), not the Worker name. Refer to [Step 1](#step-1-get-your-worker-tag) to get your Worker tag. + +For other build errors, refer to [Troubleshooting builds](/workers/ci-cd/builds/troubleshoot/). ## Related resources From d4e9dec2492356e3cb0b814d357fbf4291b476cc Mon Sep 17 00:00:00 2001 From: yomna Date: Tue, 24 Feb 2026 00:05:21 -0500 Subject: [PATCH 3/9] [Workers] Improve Builds API reference clarity and structure - Clarify user-scoped token requirement and link to build token docs - Update Worker tags section title to include external_script_id - Rewrite trigger explanation with production/preview context - Revert to ASCII diagrams for workflow overview - Restructure Examples section with diagrams for each use case - Add multiple sources for obtaining build_uuid - Fix anchor links and API reference URLs --- .../workers/ci-cd/builds/api-reference.mdx | 311 +++++++++++------- 1 file changed, 186 insertions(+), 125 deletions(-) diff --git a/src/content/docs/workers/ci-cd/builds/api-reference.mdx b/src/content/docs/workers/ci-cd/builds/api-reference.mdx index c9f25f713d1..a056a6f3550 100644 --- a/src/content/docs/workers/ci-cd/builds/api-reference.mdx +++ b/src/content/docs/workers/ci-cd/builds/api-reference.mdx @@ -1,33 +1,35 @@ --- -pcx_content_type: how-to -title: Use the Builds API +pcx_content_type: reference +title: Builds API reference description: Learn how to programmatically trigger builds, manage triggers, and monitor your Workers Builds using the API. sidebar: order: 11 --- -This guide walks you through using the Workers Builds API to programmatically manage your builds. Before diving into specific endpoints, this guide covers two important concepts that will help you get started faster. +import { Aside } from "~/components"; + +This guide shows you how to use the [Workers Builds REST API](/api/resources/workers_builds/) to programmatically trigger builds, manage triggers, and monitor build status. The examples use `curl` commands that you can run directly in your terminal or adapt to your preferred programming language. ## Before you start ### 1. Create an API token with the correct permissions -The Builds API requires a user-scoped API token with specific permissions. Create your token at [dash.cloudflare.com/profile/api-tokens](https://dash.cloudflare.com/profile/api-tokens). +To use the Builds API, you need an API token to authenticate your requests. The Builds API requires a **user-scoped** API token, account-scoped tokens are not supported and will return "Invalid token" errors. -**Required permissions:** +Create your token at [dash.cloudflare.com/profile/api-tokens](https://dash.cloudflare.com/profile/api-tokens) with the following permissions: -| Permission | Access | Why you need it | -|------------|--------|-----------------| -| Workers Builds Configuration | Edit | Trigger builds, update triggers, manage environment variables | -| Workers Scripts | Read | Retrieve Worker tags (required for all Builds API calls) | +| Permission | Access level | Why you need it | +|------------|--------------|-----------------| +| Workers Builds Configuration | Edit | Trigger builds, manage triggers, configure environment variables | +| Workers Scripts | Read | Only needed for [one endpoint](#step-1-get-your-worker-tag) to retrieve your Worker's tag (documented as [`external_script_id`](#2-worker-tags-documented-as-external_script_id)) | -:::caution[Common mistake] -If you only add the **Workers Builds Configuration** permission, you will not be able to retrieve Worker tags. You need **both** permissions. -::: + -### 2. Worker tags vs Worker names +### 2. Worker tags (documented as external_script_id) -The Builds API uses a **Worker tag** to identify Workers. In the API, this is called `external_script_id` — this is the same as the Worker tag, just with a different name. +The Builds API identifies Workers by their **tag**, an immutable UUID assigned by Cloudflare. In API responses and parameters, this value appears as `external_script_id`. | Identifier | Example | Where it comes from | |------------|---------|---------------------| @@ -36,34 +38,53 @@ The Builds API uses a **Worker tag** to identify Workers. In the API, this is ca Every Builds API endpoint that references a Worker requires the **tag**, not the name. -## Complete workflow +### 3. What is a trigger? + +A **trigger** is a configuration that defines how your Worker gets built and deployed. It specifies the build command, deploy command, environment variables, and which branches should trigger builds. Each Worker has up to **two triggers**: one for production (runs on your [production branch](/workers/ci-cd/builds/build-branches/#change-production-branch)) and one for preview (runs on all other branches). + +**Trigger fields:** + +| Field | Type | Description | +|-------|------|-------------| +| `trigger_name` | string | Display name for the trigger | +| `build_command` | string | Command to build your project (for example, `npm run build`) | +| `deploy_command` | string | Command to deploy your Worker (for example, `npx wrangler deploy`) | +| `root_directory` | string | Path to your project root | +| `branch_includes` | array | Branch patterns that trigger builds (for example, `["main"]` or `["*"]`) | +| `branch_excludes` | array | Branch patterns to exclude | +| `path_includes` | array | File path patterns that trigger builds | +| `path_excludes` | array | File path patterns to ignore | +| `build_caching_enabled` | boolean | Enable or disable build caching | +| `environment_variables` | object | Build-time variables specific to this trigger | -Here is the typical workflow for interacting with the Builds API: +## Workflow overview + +Most Builds API operations follow this pattern: first get your Worker's tag, then get the trigger UUID, then perform build operations. ```txt ┌─────────────────────────────────────────────────────────────────┐ -│ 1. Get Worker tag (from Workers Scripts API) │ -│ GET /workers/scripts → find your Worker → note the "tag" │ +│ 1. Get Worker tag (from Workers Scripts API) │ +│ GET /workers/scripts → find your Worker → note the "tag" │ └─────────────────────────────────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────────┐ -│ 2. Get trigger UUID (using the Worker tag) │ -│ GET /builds/workers/{tag}/triggers → note "trigger_uuid" │ +│ 2. Get trigger UUID (using the Worker tag) │ +│ GET /builds/workers/{tag}/triggers → note "trigger_uuid" │ └─────────────────────────────────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────────┐ -│ 3. Do things with builds │ -│ - Trigger a build: POST /builds/triggers/{trigger_uuid}/... │ -│ - List builds: GET /builds/workers/{tag}/builds │ -│ - Get logs: GET /builds/builds/{build_uuid}/logs │ +│ 3. Do things with builds │ +│ - Trigger a build: POST /builds/triggers/{trigger_uuid}/... │ +│ - List builds: GET /builds/workers/{tag}/builds │ +│ - Get logs: GET /builds/builds/{build_uuid}/logs │ └─────────────────────────────────────────────────────────────────┘ ``` ## Step 1: Get your Worker tag -Call the Workers Scripts API to list all your Workers and find the `tag` for the Worker you want to work with: +Call the [Workers Scripts API](/api/resources/workers/subresources/scripts/methods/list/) to list all your Workers and find the `tag` for the Worker you want to work with: ```bash curl -s "https://api.cloudflare.com/client/v4/accounts/{account_id}/workers/scripts" \ @@ -88,20 +109,7 @@ Save the `tag` value for your Worker. You will use it in all subsequent API call ## Step 2: Get your trigger UUID -Each Worker can have a maximum of two triggers: - -| Trigger type | Purpose | Typical branch pattern | -|--------------|---------|------------------------| -| **Production** | Deploys to your live Worker | `main` or `master` | -| **Preview** | Creates preview deployments for testing | `*` (all branches except production) | - -:::note -The two-trigger limit is enforced by the API. If you attempt to create a third trigger, the request will fail. -::: - -Each trigger has its own configuration, including separate build commands, deploy commands, and environment variables. This allows you to have different settings for production and preview builds (for example, different `NODE_ENV` values or API keys). - -Use the Worker tag to list triggers: +Use the [`GET /builds/workers/{tag}/triggers`](/api/resources/workers_builds/subresources/triggers/methods/list/) endpoint to list triggers for your Worker: ```bash curl -s "https://api.cloudflare.com/client/v4/accounts/{account_id}/builds/workers/{worker_tag}/triggers" \ @@ -134,7 +142,7 @@ Now that you have the Worker tag and trigger UUID, you can trigger builds, list ### Trigger a manual build -Use the `trigger_uuid` from [Step 2](#step-2-get-your-trigger-uuid). +Use the [`POST /builds/triggers/{uuid}/builds`](/api/resources/workers_builds/subresources/builds/methods/create/) endpoint with the `trigger_uuid` from [Step 2](#step-2-get-your-trigger-uuid). ```bash curl -s "https://api.cloudflare.com/client/v4/accounts/{account_id}/builds/triggers/{trigger_uuid}/builds" \ @@ -155,7 +163,7 @@ The response includes the `build_uuid` which you can use to monitor the build. ### List builds for a Worker -Use the `worker_tag` from [Step 1](#step-1-get-your-worker-tag). +Use the [`GET /builds/workers/{tag}/builds`](/api/resources/workers_builds/subresources/builds/methods/list/) endpoint with the `worker_tag` from [Step 1](#step-1-get-your-worker-tag). ```bash curl -s "https://api.cloudflare.com/client/v4/accounts/{account_id}/builds/workers/{worker_tag}/builds" \ @@ -167,7 +175,11 @@ The response includes `build_uuid` for each build, which you need for getting lo ### Get build logs -Use the `build_uuid` from [List builds](#list-builds-for-a-worker) or from the response when triggering a build. +Use the [`GET /builds/builds/{uuid}/logs`](/api/resources/workers_builds/subresources/builds/methods/get_logs/) endpoint. Get the `build_uuid` from: +- [List builds](#list-builds-for-a-worker) +- The response when [triggering a build](#trigger-a-manual-build) +- [Get latest builds by script IDs](/api/resources/workers_builds/subresources/builds/methods/get_latest_by_script_ids/) +- The last segment of the URL on your build details page in the dashboard ```bash curl -s "https://api.cloudflare.com/client/v4/accounts/{account_id}/builds/builds/{build_uuid}/logs" \ @@ -176,7 +188,11 @@ curl -s "https://api.cloudflare.com/client/v4/accounts/{account_id}/builds/build ### Cancel a running build -Use the `build_uuid` from [List builds](#list-builds-for-a-worker) or from the response when triggering a build. +Use the [`PUT /builds/builds/{uuid}/cancel`](/api/resources/workers_builds/subresources/builds/methods/cancel/) endpoint. Get the `build_uuid` from: +- [List builds](#list-builds-for-a-worker) +- The response when [triggering a build](#trigger-a-manual-build) +- [Get latest builds by script IDs](/api/resources/workers_builds/subresources/builds/methods/get_latest_by_script_ids/) +- The last segment of the URL on your build details page in the dashboard ```bash curl -s "https://api.cloudflare.com/client/v4/accounts/{account_id}/builds/builds/{build_uuid}/cancel" \ @@ -186,7 +202,7 @@ curl -s "https://api.cloudflare.com/client/v4/accounts/{account_id}/builds/build ## Update trigger configuration -Use the `trigger_uuid` from [Step 2](#step-2-get-your-trigger-uuid). +Use the [`PATCH /builds/triggers/{uuid}`](/api/resources/workers_builds/subresources/triggers/methods/update/) endpoint with the `trigger_uuid` from [Step 2](#step-2-get-your-trigger-uuid). You can update any of the trigger fields described in [Understand triggers](#3-understand-triggers). ```bash curl -s "https://api.cloudflare.com/client/v4/accounts/{account_id}/builds/triggers/{trigger_uuid}" \ @@ -199,27 +215,13 @@ curl -s "https://api.cloudflare.com/client/v4/accounts/{account_id}/builds/trigg }' ``` -**Editable fields:** - -| Field | Type | Description | -|-------|------|-------------| -| `trigger_name` | string | Display name for the trigger | -| `build_command` | string | Command to build your project | -| `deploy_command` | string | Command to deploy your Worker | -| `root_directory` | string | Path to your project root | -| `branch_includes` | array | Branch patterns to trigger builds | -| `branch_excludes` | array | Branch patterns to exclude | -| `path_includes` | array | File path patterns that trigger builds | -| `path_excludes` | array | File path patterns to ignore | -| `build_caching_enabled` | boolean | Turn on or off build caching | - ## Manage build environment variables -Environment variables are set per trigger, meaning you can have different values for production and preview builds. For example, you might set `NODE_ENV=production` on your production trigger and `NODE_ENV=development` on your preview trigger. +Environment variables are set per trigger, meaning you can have different values for production and preview builds. For example, you might set `NODE_ENV=production` on your production trigger and `NODE_ENV=development` on your preview trigger. Refer to the [environment variables API reference](/api/resources/workers_builds/subresources/environment_variables/) for full endpoint details. -:::note + ### List environment variables @@ -276,7 +278,7 @@ curl -s "https://api.cloudflare.com/client/v4/accounts/{account_id}/builds/trigg ## Purge build cache -Use the `trigger_uuid` from [Step 2](#step-2-get-your-trigger-uuid). This clears cached dependencies and build artifacts for that trigger. +Use the [`POST /builds/triggers/{uuid}/purge_build_cache`](/api/resources/workers_builds/subresources/triggers/methods/purge_build_cache/) endpoint with the `trigger_uuid` from [Step 2](#step-2-get-your-trigger-uuid). This clears cached dependencies and build artifacts for that trigger. ```bash curl -s "https://api.cloudflare.com/client/v4/accounts/{account_id}/builds/triggers/{trigger_uuid}/purge_build_cache" \ @@ -284,68 +286,54 @@ curl -s "https://api.cloudflare.com/client/v4/accounts/{account_id}/builds/trigg --request POST ``` -## Example: Redeploy script - -A common use case is creating a script that redeploys your current active deployment to refresh build-time data. This script demonstrates chaining multiple API calls together: - -```js -async function redeploy() { - const accountId = ""; - const workerName = ""; - const apiToken = process.env.CF_API_TOKEN; - - // Step 1: Get the active deployment's version ID - const deploymentsResponse = await fetch( - `https://api.cloudflare.com/client/v4/accounts/${accountId}/workers/scripts/${workerName}/deployments`, - { - headers: { Authorization: `Bearer ${apiToken}` }, - } - ); - const deployments = await deploymentsResponse.json(); - const versionId = deployments.result.deployments[0].versions[0].version_id; +## Examples - // Step 2: Get the build that created this version - const buildsResponse = await fetch( - `https://api.cloudflare.com/client/v4/accounts/${accountId}/builds/builds?version_ids=${versionId}`, - { - headers: { Authorization: `Bearer ${apiToken}` }, - } - ); - const buildsByVersion = await buildsResponse.json(); - const build = buildsByVersion.result.builds[versionId]; +The following examples show common use cases for the Builds API. - // Step 3: Retrigger using the same trigger, branch, and commit - await fetch( - `https://api.cloudflare.com/client/v4/accounts/${accountId}/builds/triggers/${build.trigger.trigger_uuid}/builds`, - { - method: "POST", - headers: { - Authorization: `Bearer ${apiToken}`, - "Content-Type": "application/json", - }, - body: JSON.stringify({ - branch: build.build_trigger_metadata.branch, - commit_hash: build.build_trigger_metadata.commit_hash, - }), - } - ); +### Set up Workers Builds from scratch - console.log("Redeploy triggered successfully"); -} +This example walks through the complete process of connecting a GitHub repository to a Worker and setting up automated builds using only the API. -redeploy(); +```txt +┌─────────────────────────────────────────────────────────────────┐ +│ 1. Get GitHub account and repo IDs │ +│ GET api.github.com/users/... → note account ID │ +│ GET api.github.com/repos/... → note repo ID │ +└─────────────────────────────────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────────────┐ +│ 2. Create repo connection │ +│ PUT /builds/repos/connections → note "repo_connection_uuid" │ +└─────────────────────────────────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────────────┐ +│ 3. Get Worker tag │ +│ GET /workers/scripts → note "tag" │ +└─────────────────────────────────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────────────┐ +│ 4. Create triggers │ +│ POST /builds/triggers → create production trigger │ +│ POST /builds/triggers → create preview trigger (optional) │ +└─────────────────────────────────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────────────┐ +│ 5. Set environment variables (optional) │ +│ PATCH /builds/triggers/{uuid}/environment_variables │ +└─────────────────────────────────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────────────┐ +│ 6. Trigger first build │ +│ POST /builds/triggers/{uuid}/builds │ +└─────────────────────────────────────────────────────────────────┘ ``` -This script: -1. Gets the currently deployed version from the Workers deployments API -2. Finds the build that created that version using `version_ids` query parameter -3. Triggers a new build with the same branch and commit - -## Example: Set up Workers Builds from scratch - -This example walks through the complete process of connecting a GitHub repository to a Worker and setting up automated builds using only the API. - -### Prerequisites +#### Prerequisites Before using the API, you must first install the Cloudflare GitHub App through the dashboard: @@ -355,7 +343,7 @@ Before using the API, you must first install the Cloudflare GitHub App through t This one-time setup creates the connection between your GitHub account and Cloudflare. Once complete, you can use the API for everything else. -### Step 1: Get your GitHub account information +#### Step 1: Get your GitHub account information After installing the GitHub App, you need your GitHub account ID and repository ID. You can find these from an existing trigger or from the GitHub API. @@ -369,7 +357,7 @@ curl -s "https://api.github.com/users/" | jq '.id' curl -s "https://api.github.com/repos//" | jq '.id' ``` -### Step 2: Create a repository connection +#### Step 2: Create a repository connection Create a connection between your GitHub repository and Cloudflare: @@ -389,7 +377,7 @@ curl -s "https://api.cloudflare.com/client/v4/accounts/{account_id}/builds/repos Save the `repo_connection_uuid` from the response. -### Step 3: Get your Worker tag +#### Step 3: Get your Worker tag ```bash curl -s "https://api.cloudflare.com/client/v4/accounts/{account_id}/workers/scripts" \ @@ -397,7 +385,7 @@ curl -s "https://api.cloudflare.com/client/v4/accounts/{account_id}/workers/scri | jq '.result[] | {name: .id, tag: .tag}' ``` -### Step 4: Create a production trigger +#### Step 4: Create a production trigger Create a trigger that deploys when you push to `main`: @@ -420,7 +408,7 @@ curl -s "https://api.cloudflare.com/client/v4/accounts/{account_id}/builds/trigg }' ``` -### Step 5: Create a preview trigger (optional) +#### Step 5: Create a preview trigger (optional) Create a second trigger for preview deployments on all other branches: @@ -445,7 +433,7 @@ curl -s "https://api.cloudflare.com/client/v4/accounts/{account_id}/builds/trigg Note the different `deploy_command`: production uses `wrangler deploy` while preview uses `wrangler versions upload` to create preview URLs without affecting the live deployment. -### Step 6: Set environment variables for each trigger +#### Step 6: Set environment variables for each trigger Set production environment variables: @@ -475,7 +463,7 @@ curl -s "https://api.cloudflare.com/client/v4/accounts/{account_id}/builds/trigg }' ``` -### Step 7: Trigger your first build +#### Step 7: Trigger your first build ```bash curl -s "https://api.cloudflare.com/client/v4/accounts/{account_id}/builds/triggers/{production_trigger_uuid}/builds" \ @@ -487,6 +475,79 @@ curl -s "https://api.cloudflare.com/client/v4/accounts/{account_id}/builds/trigg Your Worker is now connected to GitHub. Future pushes to `main` will automatically trigger production deployments, and pushes to other branches will create preview deployments. +### Redeploy current deployment + +Redeploy your current active deployment to refresh build-time data. This is useful when you need to rebuild without code changes. + +```txt +┌─────────────────────────────────────────────────────────────────┐ +│ 1. Get active deployment │ +│ GET /workers/scripts/{name}/deployments → note "version_id" │ +└─────────────────────────────────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────────────┐ +│ 2. Find the build for that version │ +│ GET /builds/builds?version_ids={id} → note trigger, branch │ +└─────────────────────────────────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────────────┐ +│ 3. Retrigger with same branch and commit │ +│ POST /builds/triggers/{uuid}/builds │ +└─────────────────────────────────────────────────────────────────┘ +``` + +This script chains multiple API calls together: + +```js +async function redeploy() { + const accountId = ""; + const workerName = ""; + const apiToken = process.env.CF_API_TOKEN; + + // Step 1: Get the active deployment's version ID + const deploymentsResponse = await fetch( + `https://api.cloudflare.com/client/v4/accounts/${accountId}/workers/scripts/${workerName}/deployments`, + { + headers: { Authorization: `Bearer ${apiToken}` }, + } + ); + const deployments = await deploymentsResponse.json(); + const versionId = deployments.result.deployments[0].versions[0].version_id; + + // Step 2: Get the build that created this version + const buildsResponse = await fetch( + `https://api.cloudflare.com/client/v4/accounts/${accountId}/builds/builds?version_ids=${versionId}`, + { + headers: { Authorization: `Bearer ${apiToken}` }, + } + ); + const buildsByVersion = await buildsResponse.json(); + const build = buildsByVersion.result.builds[versionId]; + + // Step 3: Retrigger using the same trigger, branch, and commit + await fetch( + `https://api.cloudflare.com/client/v4/accounts/${accountId}/builds/triggers/${build.trigger.trigger_uuid}/builds`, + { + method: "POST", + headers: { + Authorization: `Bearer ${apiToken}`, + "Content-Type": "application/json", + }, + body: JSON.stringify({ + branch: build.build_trigger_metadata.branch, + commit_hash: build.build_trigger_metadata.commit_hash, + }), + } + ); + + console.log("Redeploy triggered successfully"); +} + +redeploy(); +``` + ## Troubleshooting ### "Resource not found" error From 1b4799f52e4261b692abb6011edab9df1bbd25ce Mon Sep 17 00:00:00 2001 From: "ask-bonk[bot]" Date: Tue, 24 Feb 2026 05:12:43 +0000 Subject: [PATCH 4/9] 3 ASCII diagrams converted to Mermaid. Co-authored-by: yomna-shousha --- .../workers/ci-cd/builds/api-reference.mdx | 235 +++++++----------- 1 file changed, 96 insertions(+), 139 deletions(-) diff --git a/src/content/docs/workers/ci-cd/builds/api-reference.mdx b/src/content/docs/workers/ci-cd/builds/api-reference.mdx index a056a6f3550..bbdc2c7ace4 100644 --- a/src/content/docs/workers/ci-cd/builds/api-reference.mdx +++ b/src/content/docs/workers/ci-cd/builds/api-reference.mdx @@ -18,22 +18,26 @@ To use the Builds API, you need an API token to authenticate your requests. The Create your token at [dash.cloudflare.com/profile/api-tokens](https://dash.cloudflare.com/profile/api-tokens) with the following permissions: -| Permission | Access level | Why you need it | -|------------|--------------|-----------------| -| Workers Builds Configuration | Edit | Trigger builds, manage triggers, configure environment variables | -| Workers Scripts | Read | Only needed for [one endpoint](#step-1-get-your-worker-tag) to retrieve your Worker's tag (documented as [`external_script_id`](#2-worker-tags-documented-as-external_script_id)) | +| Permission | Access level | Why you need it | +| ---------------------------- | ------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Workers Builds Configuration | Edit | Trigger builds, manage triggers, configure environment variables | +| Workers Scripts | Read | Only needed for [one endpoint](#step-1-get-your-worker-tag) to retrieve your Worker's tag (documented as [`external_script_id`](#2-worker-tags-documented-as-external_script_id)) | ### 2. Worker tags (documented as external_script_id) The Builds API identifies Workers by their **tag**, an immutable UUID assigned by Cloudflare. In API responses and parameters, this value appears as `external_script_id`. -| Identifier | Example | Where it comes from | -|------------|---------|---------------------| -| Worker name (`id`) | `my-worker` | The name you gave your Worker | +| Identifier | Example | Where it comes from | +| --------------------------------- | ---------------------------------- | ------------------------------------- | +| Worker name (`id`) | `my-worker` | The name you gave your Worker | | Worker tag (`external_script_id`) | `1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d` | Immutable UUID assigned by Cloudflare | Every Builds API endpoint that references a Worker requires the **tag**, not the name. @@ -44,42 +48,31 @@ A **trigger** is a configuration that defines how your Worker gets built and dep **Trigger fields:** -| Field | Type | Description | -|-------|------|-------------| -| `trigger_name` | string | Display name for the trigger | -| `build_command` | string | Command to build your project (for example, `npm run build`) | -| `deploy_command` | string | Command to deploy your Worker (for example, `npx wrangler deploy`) | -| `root_directory` | string | Path to your project root | -| `branch_includes` | array | Branch patterns that trigger builds (for example, `["main"]` or `["*"]`) | -| `branch_excludes` | array | Branch patterns to exclude | -| `path_includes` | array | File path patterns that trigger builds | -| `path_excludes` | array | File path patterns to ignore | -| `build_caching_enabled` | boolean | Enable or disable build caching | -| `environment_variables` | object | Build-time variables specific to this trigger | +| Field | Type | Description | +| ----------------------- | ------- | ------------------------------------------------------------------------ | +| `trigger_name` | string | Display name for the trigger | +| `build_command` | string | Command to build your project (for example, `npm run build`) | +| `deploy_command` | string | Command to deploy your Worker (for example, `npx wrangler deploy`) | +| `root_directory` | string | Path to your project root | +| `branch_includes` | array | Branch patterns that trigger builds (for example, `["main"]` or `["*"]`) | +| `branch_excludes` | array | Branch patterns to exclude | +| `path_includes` | array | File path patterns that trigger builds | +| `path_excludes` | array | File path patterns to ignore | +| `build_caching_enabled` | boolean | Enable or disable build caching | +| `environment_variables` | object | Build-time variables specific to this trigger | ## Workflow overview Most Builds API operations follow this pattern: first get your Worker's tag, then get the trigger UUID, then perform build operations. -```txt -┌─────────────────────────────────────────────────────────────────┐ -│ 1. Get Worker tag (from Workers Scripts API) │ -│ GET /workers/scripts → find your Worker → note the "tag" │ -└─────────────────────────────────────────────────────────────────┘ - │ - ▼ -┌─────────────────────────────────────────────────────────────────┐ -│ 2. Get trigger UUID (using the Worker tag) │ -│ GET /builds/workers/{tag}/triggers → note "trigger_uuid" │ -└─────────────────────────────────────────────────────────────────┘ - │ - ▼ -┌─────────────────────────────────────────────────────────────────┐ -│ 3. Do things with builds │ -│ - Trigger a build: POST /builds/triggers/{trigger_uuid}/... │ -│ - List builds: GET /builds/workers/{tag}/builds │ -│ - Get logs: GET /builds/builds/{build_uuid}/logs │ -└─────────────────────────────────────────────────────────────────┘ +```mermaid +flowchart TD + A["1. Get Worker tag
GET /workers/scripts
Find your Worker and note the tag UUID"] --> B["2. Get trigger UUID
GET /builds/workers/{tag}/triggers
List triggers for your Worker and note trigger_uuid"] + B --> C{"3. Perform build operations"} + C --> D["Trigger a build
POST /builds/triggers/{uuid}/builds"] + C --> E["List builds
GET /builds/workers/{tag}/builds"] + C --> F["Get build logs
GET /builds/builds/{uuid}/logs"] + C --> G["Cancel a build
PUT /builds/builds/{uuid}/cancel"] ``` ## Step 1: Get your Worker tag @@ -154,10 +147,10 @@ curl -s "https://api.cloudflare.com/client/v4/accounts/{account_id}/builds/trigg You can specify either `branch` or `commit_hash`: -| Field | Description | -|-------|-------------| -| `branch` | Git branch name to build (for example, `main`) | -| `commit_hash` | Specific commit SHA to build | +| Field | Description | +| ------------- | ---------------------------------------------- | +| `branch` | Git branch name to build (for example, `main`) | +| `commit_hash` | Specific commit SHA to build | The response includes the `build_uuid` which you can use to monitor the build. @@ -176,6 +169,7 @@ The response includes `build_uuid` for each build, which you need for getting lo ### Get build logs Use the [`GET /builds/builds/{uuid}/logs`](/api/resources/workers_builds/subresources/builds/methods/get_logs/) endpoint. Get the `build_uuid` from: + - [List builds](#list-builds-for-a-worker) - The response when [triggering a build](#trigger-a-manual-build) - [Get latest builds by script IDs](/api/resources/workers_builds/subresources/builds/methods/get_latest_by_script_ids/) @@ -189,6 +183,7 @@ curl -s "https://api.cloudflare.com/client/v4/accounts/{account_id}/builds/build ### Cancel a running build Use the [`PUT /builds/builds/{uuid}/cancel`](/api/resources/workers_builds/subresources/builds/methods/cancel/) endpoint. Get the `build_uuid` from: + - [List builds](#list-builds-for-a-worker) - The response when [triggering a build](#trigger-a-manual-build) - [Get latest builds by script IDs](/api/resources/workers_builds/subresources/builds/methods/get_latest_by_script_ids/) @@ -220,7 +215,9 @@ curl -s "https://api.cloudflare.com/client/v4/accounts/{account_id}/builds/trigg Environment variables are set per trigger, meaning you can have different values for production and preview builds. For example, you might set `NODE_ENV=production` on your production trigger and `NODE_ENV=development` on your preview trigger. Refer to the [environment variables API reference](/api/resources/workers_builds/subresources/environment_variables/) for full endpoint details. ### List environment variables @@ -294,43 +291,16 @@ The following examples show common use cases for the Builds API. This example walks through the complete process of connecting a GitHub repository to a Worker and setting up automated builds using only the API. -```txt -┌─────────────────────────────────────────────────────────────────┐ -│ 1. Get GitHub account and repo IDs │ -│ GET api.github.com/users/... → note account ID │ -│ GET api.github.com/repos/... → note repo ID │ -└─────────────────────────────────────────────────────────────────┘ - │ - ▼ -┌─────────────────────────────────────────────────────────────────┐ -│ 2. Create repo connection │ -│ PUT /builds/repos/connections → note "repo_connection_uuid" │ -└─────────────────────────────────────────────────────────────────┘ - │ - ▼ -┌─────────────────────────────────────────────────────────────────┐ -│ 3. Get Worker tag │ -│ GET /workers/scripts → note "tag" │ -└─────────────────────────────────────────────────────────────────┘ - │ - ▼ -┌─────────────────────────────────────────────────────────────────┐ -│ 4. Create triggers │ -│ POST /builds/triggers → create production trigger │ -│ POST /builds/triggers → create preview trigger (optional) │ -└─────────────────────────────────────────────────────────────────┘ - │ - ▼ -┌─────────────────────────────────────────────────────────────────┐ -│ 5. Set environment variables (optional) │ -│ PATCH /builds/triggers/{uuid}/environment_variables │ -└─────────────────────────────────────────────────────────────────┘ - │ - ▼ -┌─────────────────────────────────────────────────────────────────┐ -│ 6. Trigger first build │ -│ POST /builds/triggers/{uuid}/builds │ -└─────────────────────────────────────────────────────────────────┘ +```mermaid +flowchart TD + A["1. Get GitHub account and repo IDs
GET api.github.com/users/... → note account ID
GET api.github.com/repos/... → note repo ID"] --> B["2. Create repo connection
PUT /builds/repos/connections
Links your GitHub repo to Cloudflare
Save the repo_connection_uuid"] + B --> C["3. Get Worker tag
GET /workers/scripts
Find your Worker and note the tag UUID"] + C --> D["4. Create triggers
POST /builds/triggers"] + D --> D1["Production trigger
branch_includes: main
deploy_command: wrangler deploy"] + D --> D2["Preview trigger (optional)
branch_includes: *
branch_excludes: main
deploy_command: wrangler versions upload"] + D1 --> E["5. Set environment variables (optional)
PATCH /builds/triggers/{uuid}/environment_variables
Configure per-trigger build-time variables"] + D2 --> E + E --> F["6. Trigger first build
POST /builds/triggers/{uuid}/builds
Start your first production deployment"] ``` #### Prerequisites @@ -479,70 +449,57 @@ Your Worker is now connected to GitHub. Future pushes to `main` will automatical Redeploy your current active deployment to refresh build-time data. This is useful when you need to rebuild without code changes. -```txt -┌─────────────────────────────────────────────────────────────────┐ -│ 1. Get active deployment │ -│ GET /workers/scripts/{name}/deployments → note "version_id" │ -└─────────────────────────────────────────────────────────────────┘ - │ - ▼ -┌─────────────────────────────────────────────────────────────────┐ -│ 2. Find the build for that version │ -│ GET /builds/builds?version_ids={id} → note trigger, branch │ -└─────────────────────────────────────────────────────────────────┘ - │ - ▼ -┌─────────────────────────────────────────────────────────────────┐ -│ 3. Retrigger with same branch and commit │ -│ POST /builds/triggers/{uuid}/builds │ -└─────────────────────────────────────────────────────────────────┘ +```mermaid +flowchart TD + A["1. Get active deployment
GET /workers/scripts/{name}/deployments
Find the current live deployment
and note the version_id"] --> B["2. Find the build for that version
GET /builds/builds?version_ids={id}
Look up trigger_uuid, branch,
and commit_hash from the original build"] + B --> C["3. Retrigger with same branch and commit
POST /builds/triggers/{uuid}/builds
Rebuild using the same trigger, branch,
and commit_hash to refresh build-time data"] ``` This script chains multiple API calls together: ```js async function redeploy() { - const accountId = ""; - const workerName = ""; - const apiToken = process.env.CF_API_TOKEN; - - // Step 1: Get the active deployment's version ID - const deploymentsResponse = await fetch( - `https://api.cloudflare.com/client/v4/accounts/${accountId}/workers/scripts/${workerName}/deployments`, - { - headers: { Authorization: `Bearer ${apiToken}` }, - } - ); - const deployments = await deploymentsResponse.json(); - const versionId = deployments.result.deployments[0].versions[0].version_id; - - // Step 2: Get the build that created this version - const buildsResponse = await fetch( - `https://api.cloudflare.com/client/v4/accounts/${accountId}/builds/builds?version_ids=${versionId}`, - { - headers: { Authorization: `Bearer ${apiToken}` }, - } - ); - const buildsByVersion = await buildsResponse.json(); - const build = buildsByVersion.result.builds[versionId]; - - // Step 3: Retrigger using the same trigger, branch, and commit - await fetch( - `https://api.cloudflare.com/client/v4/accounts/${accountId}/builds/triggers/${build.trigger.trigger_uuid}/builds`, - { - method: "POST", - headers: { - Authorization: `Bearer ${apiToken}`, - "Content-Type": "application/json", - }, - body: JSON.stringify({ - branch: build.build_trigger_metadata.branch, - commit_hash: build.build_trigger_metadata.commit_hash, - }), - } - ); - - console.log("Redeploy triggered successfully"); + const accountId = ""; + const workerName = ""; + const apiToken = process.env.CF_API_TOKEN; + + // Step 1: Get the active deployment's version ID + const deploymentsResponse = await fetch( + `https://api.cloudflare.com/client/v4/accounts/${accountId}/workers/scripts/${workerName}/deployments`, + { + headers: { Authorization: `Bearer ${apiToken}` }, + }, + ); + const deployments = await deploymentsResponse.json(); + const versionId = deployments.result.deployments[0].versions[0].version_id; + + // Step 2: Get the build that created this version + const buildsResponse = await fetch( + `https://api.cloudflare.com/client/v4/accounts/${accountId}/builds/builds?version_ids=${versionId}`, + { + headers: { Authorization: `Bearer ${apiToken}` }, + }, + ); + const buildsByVersion = await buildsResponse.json(); + const build = buildsByVersion.result.builds[versionId]; + + // Step 3: Retrigger using the same trigger, branch, and commit + await fetch( + `https://api.cloudflare.com/client/v4/accounts/${accountId}/builds/triggers/${build.trigger.trigger_uuid}/builds`, + { + method: "POST", + headers: { + Authorization: `Bearer ${apiToken}`, + "Content-Type": "application/json", + }, + body: JSON.stringify({ + branch: build.build_trigger_metadata.branch, + commit_hash: build.build_trigger_metadata.commit_hash, + }), + }, + ); + + console.log("Redeploy triggered successfully"); } redeploy(); From 14e3049893864f4e8d16f9b4ec65896715ad7df6 Mon Sep 17 00:00:00 2001 From: yomna Date: Tue, 24 Feb 2026 01:13:01 -0500 Subject: [PATCH 5/9] [Workers] Fix broken anchor link to trigger section MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Fix anchor link (#3-understand-triggers → #3-what-is-a-trigger) --- src/content/docs/workers/ci-cd/builds/api-reference.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/content/docs/workers/ci-cd/builds/api-reference.mdx b/src/content/docs/workers/ci-cd/builds/api-reference.mdx index bbdc2c7ace4..5934a097f6b 100644 --- a/src/content/docs/workers/ci-cd/builds/api-reference.mdx +++ b/src/content/docs/workers/ci-cd/builds/api-reference.mdx @@ -197,7 +197,7 @@ curl -s "https://api.cloudflare.com/client/v4/accounts/{account_id}/builds/build ## Update trigger configuration -Use the [`PATCH /builds/triggers/{uuid}`](/api/resources/workers_builds/subresources/triggers/methods/update/) endpoint with the `trigger_uuid` from [Step 2](#step-2-get-your-trigger-uuid). You can update any of the trigger fields described in [Understand triggers](#3-understand-triggers). +Use the [`PATCH /builds/triggers/{uuid}`](/api/resources/workers_builds/subresources/triggers/methods/update/) endpoint with the `trigger_uuid` from [Step 2](#step-2-get-your-trigger-uuid). You can update any of the trigger fields described in [What is a trigger?](#3-what-is-a-trigger). ```bash curl -s "https://api.cloudflare.com/client/v4/accounts/{account_id}/builds/triggers/{trigger_uuid}" \ From 4346c09b874259c8bf7ed94ef87ba984c6daacaa Mon Sep 17 00:00:00 2001 From: "ask-bonk[bot]" Date: Tue, 24 Feb 2026 06:23:01 +0000 Subject: [PATCH 6/9] Fixed 3 Mermaid diagrams: fields, style Co-authored-by: yomna-shousha --- .../workers/ci-cd/builds/api-reference.mdx | 32 +++++++++---------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/src/content/docs/workers/ci-cd/builds/api-reference.mdx b/src/content/docs/workers/ci-cd/builds/api-reference.mdx index 5934a097f6b..cb1ef7d8d46 100644 --- a/src/content/docs/workers/ci-cd/builds/api-reference.mdx +++ b/src/content/docs/workers/ci-cd/builds/api-reference.mdx @@ -67,12 +67,12 @@ Most Builds API operations follow this pattern: first get your Worker's tag, the ```mermaid flowchart TD - A["1. Get Worker tag
GET /workers/scripts
Find your Worker and note the tag UUID"] --> B["2. Get trigger UUID
GET /builds/workers/{tag}/triggers
List triggers for your Worker and note trigger_uuid"] - B --> C{"3. Perform build operations"} - C --> D["Trigger a build
POST /builds/triggers/{uuid}/builds"] - C --> E["List builds
GET /builds/workers/{tag}/builds"] - C --> F["Get build logs
GET /builds/builds/{uuid}/logs"] - C --> G["Cancel a build
PUT /builds/builds/{uuid}/cancel"] + A["1. Get Worker tag
GET /workers/scripts"] --> B["2. Get trigger UUID
GET /builds/workers/{worker_tag}/triggers"] + B --> C{"3. Perform build operations"} + C --> D["Trigger a build
POST /builds/triggers/{trigger_uuid}/builds"] + C --> E["List builds
GET /builds/workers/{worker_tag}/builds"] + C --> F["Get build logs
GET /builds/builds/{build_uuid}/logs"] + C --> G["Cancel a build
PUT /builds/builds/{build_uuid}/cancel"] ``` ## Step 1: Get your Worker tag @@ -293,14 +293,14 @@ This example walks through the complete process of connecting a GitHub repositor ```mermaid flowchart TD - A["1. Get GitHub account and repo IDs
GET api.github.com/users/... → note account ID
GET api.github.com/repos/... → note repo ID"] --> B["2. Create repo connection
PUT /builds/repos/connections
Links your GitHub repo to Cloudflare
Save the repo_connection_uuid"] - B --> C["3. Get Worker tag
GET /workers/scripts
Find your Worker and note the tag UUID"] - C --> D["4. Create triggers
POST /builds/triggers"] - D --> D1["Production trigger
branch_includes: main
deploy_command: wrangler deploy"] - D --> D2["Preview trigger (optional)
branch_includes: *
branch_excludes: main
deploy_command: wrangler versions upload"] - D1 --> E["5. Set environment variables (optional)
PATCH /builds/triggers/{uuid}/environment_variables
Configure per-trigger build-time variables"] + A["1. Get GitHub account and repo IDs
GET api.github.com/users/... → note account ID
GET api.github.com/repos/... → note repo ID"] --> B["2. Create repo connection
PUT /builds/repos/connections"] + B --> C["3. Get Worker tag
GET /workers/scripts"] + C --> D["4. Create triggers
POST /builds/triggers"] + D --> D1["Production trigger
branch_includes: main
deploy_command: wrangler deploy"] + D --> D2["Preview trigger (optional)
branch_includes: *
branch_excludes: main
deploy_command: wrangler versions upload"] + D1 --> E["5. Set environment variables (optional)
PATCH /builds/triggers/{trigger_uuid}/environment_variables"] D2 --> E - E --> F["6. Trigger first build
POST /builds/triggers/{uuid}/builds
Start your first production deployment"] + E --> F["6. Trigger first build
POST /builds/triggers/{trigger_uuid}/builds"] ``` #### Prerequisites @@ -450,9 +450,9 @@ Your Worker is now connected to GitHub. Future pushes to `main` will automatical Redeploy your current active deployment to refresh build-time data. This is useful when you need to rebuild without code changes. ```mermaid -flowchart TD - A["1. Get active deployment
GET /workers/scripts/{name}/deployments
Find the current live deployment
and note the version_id"] --> B["2. Find the build for that version
GET /builds/builds?version_ids={id}
Look up trigger_uuid, branch,
and commit_hash from the original build"] - B --> C["3. Retrigger with same branch and commit
POST /builds/triggers/{uuid}/builds
Rebuild using the same trigger, branch,
and commit_hash to refresh build-time data"] +flowchart LR + A["1. Get active deployment
GET /workers/scripts/{worker_name}/deployments"] --> B["2. Find the build for that version
GET /builds/builds?version_ids={version_id}"] + B --> C["3. Retrigger with same branch and commit
POST /builds/triggers/{trigger_uuid}/builds"] ``` This script chains multiple API calls together: From d0eda807ba09abb88fec2a49534d39ade9b1abe0 Mon Sep 17 00:00:00 2001 From: yomna Date: Mon, 30 Mar 2026 11:08:04 -0400 Subject: [PATCH 7/9] [Workers] Standardize redeploy example to curl, add SVG workflow diagrams --- .../images/workers/builds/redeploy-flow.svg | 43 ++++++ .../workers/builds/setup-from-scratch.svg | 75 ++++++++++ .../workers/builds/workflow-overview.svg | 46 ++++++ .../workers/ci-cd/builds/api-reference.mdx | 134 ++++++++---------- 4 files changed, 227 insertions(+), 71 deletions(-) create mode 100644 src/assets/images/workers/builds/redeploy-flow.svg create mode 100644 src/assets/images/workers/builds/setup-from-scratch.svg create mode 100644 src/assets/images/workers/builds/workflow-overview.svg diff --git a/src/assets/images/workers/builds/redeploy-flow.svg b/src/assets/images/workers/builds/redeploy-flow.svg new file mode 100644 index 00000000000..9dcf61f6151 --- /dev/null +++ b/src/assets/images/workers/builds/redeploy-flow.svg @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + Step 1 + Get active deployment + Find current version ID + + + + + + + Step 2 + Find the build + Look up by version ID + + + + + + + Step 3 + Retrigger build + Same branch & commit + \ No newline at end of file diff --git a/src/assets/images/workers/builds/setup-from-scratch.svg b/src/assets/images/workers/builds/setup-from-scratch.svg new file mode 100644 index 00000000000..38b57338072 --- /dev/null +++ b/src/assets/images/workers/builds/setup-from-scratch.svg @@ -0,0 +1,75 @@ + + + + + + + + + + + + + + + + Step 1 + Get GitHub IDs + Account ID & repo ID + + + + + + + Step 2 + Create repo connection + Link GitHub to Cloudflare + + + + + + + Step 3 + Get Worker tag + Find your Worker's UUID + + + + + + + + + Step 4 + Create triggers + Production & preview + + + + + + + Step 5 + Set env variables + Per-trigger (optional) + + + + + + + + Step 6 + Trigger first build + \ No newline at end of file diff --git a/src/assets/images/workers/builds/workflow-overview.svg b/src/assets/images/workers/builds/workflow-overview.svg new file mode 100644 index 00000000000..8e8c8ba6a9b --- /dev/null +++ b/src/assets/images/workers/builds/workflow-overview.svg @@ -0,0 +1,46 @@ + + + + + + + + + + + + + + + + Step 1 + Get Worker tag + GET /workers/scripts + + + + + + + Step 2 + Get trigger UUID + GET .../triggers + + + + + + + Step 3 + Build operations + Trigger / List / Logs + \ No newline at end of file diff --git a/src/content/docs/workers/ci-cd/builds/api-reference.mdx b/src/content/docs/workers/ci-cd/builds/api-reference.mdx index cb1ef7d8d46..0f8bc469752 100644 --- a/src/content/docs/workers/ci-cd/builds/api-reference.mdx +++ b/src/content/docs/workers/ci-cd/builds/api-reference.mdx @@ -65,15 +65,16 @@ A **trigger** is a configuration that defines how your Worker gets built and dep Most Builds API operations follow this pattern: first get your Worker's tag, then get the trigger UUID, then perform build operations. -```mermaid -flowchart TD - A["1. Get Worker tag
GET /workers/scripts"] --> B["2. Get trigger UUID
GET /builds/workers/{worker_tag}/triggers"] - B --> C{"3. Perform build operations"} - C --> D["Trigger a build
POST /builds/triggers/{trigger_uuid}/builds"] - C --> E["List builds
GET /builds/workers/{worker_tag}/builds"] - C --> F["Get build logs
GET /builds/builds/{build_uuid}/logs"] - C --> G["Cancel a build
PUT /builds/builds/{build_uuid}/cancel"] -``` +![Workflow overview: get Worker tag, then get trigger UUID, then perform build operations.](~/assets/images/workers/builds/workflow-overview.svg) + +| Step | Action | Endpoint | +| ---- | ------------------- | ----------------------------------------------------- | +| 1 | Get Worker tag | `GET /workers/scripts` | +| 2 | Get trigger UUID | `GET /builds/workers/:worker_tag/triggers` | +| 3a | Trigger a build | `POST /builds/triggers/:trigger_uuid/builds` | +| 3b | List builds | `GET /builds/workers/:worker_tag/builds` | +| 3c | Get build logs | `GET /builds/builds/:build_uuid/logs` | +| 3d | Cancel a build | `PUT /builds/builds/:build_uuid/cancel` | ## Step 1: Get your Worker tag @@ -291,17 +292,17 @@ The following examples show common use cases for the Builds API. This example walks through the complete process of connecting a GitHub repository to a Worker and setting up automated builds using only the API. -```mermaid -flowchart TD - A["1. Get GitHub account and repo IDs
GET api.github.com/users/... → note account ID
GET api.github.com/repos/... → note repo ID"] --> B["2. Create repo connection
PUT /builds/repos/connections"] - B --> C["3. Get Worker tag
GET /workers/scripts"] - C --> D["4. Create triggers
POST /builds/triggers"] - D --> D1["Production trigger
branch_includes: main
deploy_command: wrangler deploy"] - D --> D2["Preview trigger (optional)
branch_includes: *
branch_excludes: main
deploy_command: wrangler versions upload"] - D1 --> E["5. Set environment variables (optional)
PATCH /builds/triggers/{trigger_uuid}/environment_variables"] - D2 --> E - E --> F["6. Trigger first build
POST /builds/triggers/{trigger_uuid}/builds"] -``` +![Setup flow: get GitHub IDs, create repo connection, get Worker tag, create triggers, set env variables, trigger first build.](~/assets/images/workers/builds/setup-from-scratch.svg) + +| Step | Action | Endpoint | +| ---- | --------------------------- | ----------------------------------------------------------------- | +| 1 | Get GitHub account/repo IDs | `GET api.github.com/users/...` and `GET api.github.com/repos/...` | +| 2 | Create repo connection | `PUT /builds/repos/connections` | +| 3 | Get Worker tag | `GET /workers/scripts` | +| 4a | Create production trigger | `POST /builds/triggers` | +| 4b | Create preview trigger | `POST /builds/triggers` | +| 5 | Set environment variables | `PATCH /builds/triggers/:trigger_uuid/environment_variables` | +| 6 | Trigger first build | `POST /builds/triggers/:trigger_uuid/builds` | #### Prerequisites @@ -449,60 +450,51 @@ Your Worker is now connected to GitHub. Future pushes to `main` will automatical Redeploy your current active deployment to refresh build-time data. This is useful when you need to rebuild without code changes. -```mermaid -flowchart LR - A["1. Get active deployment
GET /workers/scripts/{worker_name}/deployments"] --> B["2. Find the build for that version
GET /builds/builds?version_ids={version_id}"] - B --> C["3. Retrigger with same branch and commit
POST /builds/triggers/{trigger_uuid}/builds"] +![Redeploy flow: get active deployment, find the build for that version, retrigger with same branch and commit.](~/assets/images/workers/builds/redeploy-flow.svg) + +| Step | Action | Endpoint | +| ---- | --------------------------------- | ----------------------------------------------------- | +| 1 | Get active deployment | `GET /workers/scripts/:worker_name/deployments` | +| 2 | Find the build for that version | `GET /builds/builds?version_ids=:version_id` | +| 3 | Retrigger with same branch/commit | `POST /builds/triggers/:trigger_uuid/builds` | + +**Step 1: Get the active deployment's version ID** + +Use the [`GET /workers/scripts/{script_name}/deployments`](/api/resources/workers/subresources/scripts/subresources/deployments/methods/list/) endpoint with the `worker_name` from [Step 1](#step-1-get-your-worker-tag): + +```bash +curl -s "https://api.cloudflare.com/client/v4/accounts/{account_id}/workers/scripts/{worker_name}/deployments" \ + --header "Authorization: Bearer " \ + | jq '.result.deployments[0].versions[0].version_id' ``` -This script chains multiple API calls together: - -```js -async function redeploy() { - const accountId = ""; - const workerName = ""; - const apiToken = process.env.CF_API_TOKEN; - - // Step 1: Get the active deployment's version ID - const deploymentsResponse = await fetch( - `https://api.cloudflare.com/client/v4/accounts/${accountId}/workers/scripts/${workerName}/deployments`, - { - headers: { Authorization: `Bearer ${apiToken}` }, - }, - ); - const deployments = await deploymentsResponse.json(); - const versionId = deployments.result.deployments[0].versions[0].version_id; - - // Step 2: Get the build that created this version - const buildsResponse = await fetch( - `https://api.cloudflare.com/client/v4/accounts/${accountId}/builds/builds?version_ids=${versionId}`, - { - headers: { Authorization: `Bearer ${apiToken}` }, - }, - ); - const buildsByVersion = await buildsResponse.json(); - const build = buildsByVersion.result.builds[versionId]; - - // Step 3: Retrigger using the same trigger, branch, and commit - await fetch( - `https://api.cloudflare.com/client/v4/accounts/${accountId}/builds/triggers/${build.trigger.trigger_uuid}/builds`, - { - method: "POST", - headers: { - Authorization: `Bearer ${apiToken}`, - "Content-Type": "application/json", - }, - body: JSON.stringify({ - branch: build.build_trigger_metadata.branch, - commit_hash: build.build_trigger_metadata.commit_hash, - }), - }, - ); - - console.log("Redeploy triggered successfully"); -} +Save the `version_id` from the output. -redeploy(); +**Step 2: Find the build for that version** + +Use the [`GET /builds/builds`](/api/resources/workers_builds/subresources/builds/methods/get_by_version_ids/) endpoint with the `version_id` from the previous step: + +```bash +curl -s "https://api.cloudflare.com/client/v4/accounts/{account_id}/builds/builds?version_ids={version_id}" \ + --header "Authorization: Bearer " \ + | jq '.result.builds' +``` + +From the response, note the `trigger.trigger_uuid`, `build_trigger_metadata.branch`, and `build_trigger_metadata.commit_hash`. + +**Step 3: Retrigger with the same branch and commit** + +Use the [`POST /builds/triggers/{uuid}/builds`](/api/resources/workers_builds/subresources/builds/methods/create/) endpoint with the values from the previous step: + +```bash +curl -s "https://api.cloudflare.com/client/v4/accounts/{account_id}/builds/triggers/{trigger_uuid}/builds" \ + --header "Authorization: Bearer " \ + --header "Content-Type: application/json" \ + --request POST \ + --data '{ + "branch": "{branch}", + "commit_hash": "{commit_hash}" + }' ``` ## Troubleshooting From ffbfd7a004673d347c69c8293ede522218e5ac3f Mon Sep 17 00:00:00 2001 From: yomna Date: Mon, 30 Mar 2026 13:06:41 -0400 Subject: [PATCH 8/9] [Workers] Address Greg's review comments on Builds API reference --- .../workers/ci-cd/builds/api-reference.mdx | 10 +- .../workers/ci-cd/builds/preview-builds.mdx | 155 ++++++++++++++++++ 2 files changed, 161 insertions(+), 4 deletions(-) create mode 100644 src/content/docs/workers/ci-cd/builds/preview-builds.mdx diff --git a/src/content/docs/workers/ci-cd/builds/api-reference.mdx b/src/content/docs/workers/ci-cd/builds/api-reference.mdx index 0f8bc469752..a0f46440161 100644 --- a/src/content/docs/workers/ci-cd/builds/api-reference.mdx +++ b/src/content/docs/workers/ci-cd/builds/api-reference.mdx @@ -8,7 +8,7 @@ sidebar: import { Aside } from "~/components"; -This guide shows you how to use the [Workers Builds REST API](/api/resources/workers_builds/) to programmatically trigger builds, manage triggers, and monitor build status. The examples use `curl` commands that you can run directly in your terminal or adapt to your preferred programming language. +This guide shows you how to use the [Workers Builds REST API](/api/resources/workers_builds/) to programmatically trigger builds, manage triggers, and monitor build status. The examples use `curl` commands that you can run directly in your terminal or adapt to your preferred programming language. Some examples pipe output through [`jq`](https://jqlang.org/) to filter JSON responses — install it if you do not have it already. ## Before you start @@ -44,7 +44,7 @@ Every Builds API endpoint that references a Worker requires the **tag**, not the ### 3. What is a trigger? -A **trigger** is a configuration that defines how your Worker gets built and deployed. It specifies the build command, deploy command, environment variables, and which branches should trigger builds. Each Worker has up to **two triggers**: one for production (runs on your [production branch](/workers/ci-cd/builds/build-branches/#change-production-branch)) and one for preview (runs on all other branches). +A **trigger** is a configuration that defines how your Worker gets built and deployed. It specifies the build command, deploy command, environment variables, and which branches should trigger builds. Each Worker has up to **two triggers**: one for production (runs on your [production branch](/workers/ci-cd/builds/build-branches/#change-production-branch)) and one for preview (runs on all other branches). To set up triggers, refer to [Set up Workers Builds from scratch](#set-up-workers-builds-from-scratch). **Trigger fields:** @@ -146,12 +146,12 @@ curl -s "https://api.cloudflare.com/client/v4/accounts/{account_id}/builds/trigg --data '{"branch": "main"}' ``` -You can specify either `branch` or `commit_hash`: +You must specify `branch`, `commit_hash`, or both: | Field | Description | | ------------- | ---------------------------------------------- | | `branch` | Git branch name to build (for example, `main`) | -| `commit_hash` | Specific commit SHA to build | +| `commit_hash` | Specific commit SHA to build. If provided without `branch`, builds the commit on its current branch. | The response includes the `build_uuid` which you can use to monitor the build. @@ -495,6 +495,8 @@ curl -s "https://api.cloudflare.com/client/v4/accounts/{account_id}/builds/trigg "branch": "{branch}", "commit_hash": "{commit_hash}" }' + +Passing both `branch` and `commit_hash` pins the build to that exact commit on that branch. ``` ## Troubleshooting diff --git a/src/content/docs/workers/ci-cd/builds/preview-builds.mdx b/src/content/docs/workers/ci-cd/builds/preview-builds.mdx new file mode 100644 index 00000000000..f2dd02fa9ab --- /dev/null +++ b/src/content/docs/workers/ci-cd/builds/preview-builds.mdx @@ -0,0 +1,155 @@ +--- +pcx_content_type: concept +title: Preview builds +description: Understand how Workers Builds creates isolated preview environments for feature branches using Worker Previews. +sidebar: + order: 7 +--- + +import { Render, Tabs, TabItem } from "~/components"; + +When you enable non-production branch builds, every push to a feature branch creates an isolated **Worker Preview** — a fully functional copy of your Worker with its own bindings, environment variables, secrets, and URL. This lets your team test changes in a production-like environment without affecting live traffic or production data. + +## How preview builds work + +When you push to a non-production branch: + +1. Workers Builds detects the push event from your connected Git repository. +2. A build runs your configured build command (for example, `npm run build`). +3. The build system creates a **Worker Preview** — an isolated child Worker named after your branch. +4. Your code is deployed to the Preview with its own set of bindings and secrets. +5. A PR/MR comment is posted with the preview URL. + +The preview URL follows the format: + +``` +https://-..workers.dev +``` + +Each subsequent push to the same branch updates the existing Preview with a new deployment. The preview URL stays stable — it always points to the latest deployment on that branch. + +:::note +Worker Previews are different from [Preview URLs](/workers/configuration/previews/). Preview URLs generate a versioned URL for each Worker version but share production bindings. Worker Previews create fully isolated environments with their own configuration. +::: + +## What changes for existing Builds users + +If you have been using non-production branch builds with the default `wrangler versions upload` command, enabling Worker Previews upgrades your branch preview experience: + +| | Before (Preview URLs) | After (Worker Previews) | +|---|---|---| +| **What gets created** | A versioned URL pointing to your production Worker | An isolated child Worker with its own environment | +| **Bindings and secrets** | Same as production | Configured separately via Preview Defaults | +| **Branch URL** | `-..workers.dev` | `-..workers.dev` | +| **Commit URL** | `-..workers.dev` | `-..workers.dev` | +| **Observability** | Shares production settings | Independently configurable | +| **PR comments** | Shows branch and commit preview URLs | Shows Preview URL and deployment URL | + +The branch preview URL format stays the same, so existing bookmarks and integrations continue to work. The key difference is that your preview now runs with its own isolated configuration instead of sharing production secrets and bindings. + +## Enable preview builds + +To enable preview builds with Worker Previews: + +1. Go to **Workers & Pages** > your Worker > **Settings** > **Build**. +2. Under **Branch control**, enable **Builds for non-production branches**. +3. Select **Enable preview builds**. This updates your non-production branch deploy command to use Worker Previews. + +Once enabled, your build configuration will show Worker Previews as active. Every push to a feature branch will create or update an isolated Preview environment. + +## Configure Preview Defaults + +Preview Defaults define the bindings, variables, secrets, and observability settings that every new Preview starts with. Configure these once, and all branch previews inherit them automatically. + +### From the dashboard + +1. Go to **Workers & Pages** > your Worker > **Settings**. +2. Switch between the **Production** and **Previews** tabs to configure each environment independently. +3. For each binding or variable, you can either use the production value or set a preview-specific value. + +For example, you might point your KV binding at a staging namespace for Previews while keeping production pointed at your live namespace. + +### From Wrangler + +Add a `previews` block to your `wrangler.json` to define preview-specific overrides: + +```json +{ + "name": "my-worker", + "vars": { + "ENVIRONMENT": "production", + "API_URL": "https://api.example.com" + }, + "kv_namespaces": [ + { "binding": "MY_KV", "id": "production-kv-id" } + ], + "previews": { + "vars": { + "ENVIRONMENT": "preview", + "API_URL": "https://api.staging.example.com" + }, + "kv_namespaces": [ + { "binding": "MY_KV", "id": "staging-kv-id" } + ] + } +} +``` + +Values in the `previews` block override the top-level values for Preview deployments. Any binding not specified in `previews` falls back to its Preview Default (configured in the dashboard) or is omitted. + +To sync your `wrangler.json` preview settings to the dashboard: + +```sh +npx wrangler preview settings update +``` + +### Keeping environments in sync + +When you add a new binding or variable to production, your Previews environment may fall out of sync. The dashboard will show an **Import** action on the Bindings or Settings tab when it detects missing configuration. Use this to copy new bindings from production into your Preview Defaults — you can choose to use the production value as-is or set a preview-specific value for each one. + +## Preview secrets + +Preview secrets are managed separately from production secrets. Add a secret that only Previews can access: + +```sh +npx wrangler preview secret put MY_SECRET +``` + +List all Preview secrets: + +```sh +npx wrangler preview secret list +``` + +Preview secrets are stored in Preview Defaults and inherited by all Previews. They never appear in production configuration. + +## View and manage Previews + +Active Previews appear in the **Previews** tab of your Worker in the dashboard. Each Preview shows: + +- The branch it was created from +- The stable preview URL +- Recent deployments +- Observability and settings + +You can also manage Previews from the CLI: + +```sh +# Delete a Preview and all its deployments +npx wrangler preview delete + +# Delete a specific Preview by name +npx wrangler preview delete --name feature-branch +``` + +## Automatic cleanup + +Previews can be configured to auto-delete when their tracking branch is deleted from the repository. This setting is available per-Preview in the dashboard under the Preview's **Settings** tab. + +Previews also have a maximum limit per Worker. When the limit is reached, the least recently deployed Preview is automatically removed. + +## Limitations + +- [Service bindings](/workers/runtime-apis/bindings/service-bindings/) in a Preview always target the **production** instance of the bound Worker. You cannot point a service binding at another Preview. +- Non-fetch handlers (Cron Triggers, Queue consumers, etc.) cannot be invoked directly on a Preview. To test these, call the handler from a fetch handler within your Preview. +- [Durable Object](/durable-objects/) isolation in Previews requires additional API-side support that is currently being rolled out. Check the [Worker Previews documentation](/workers/previews/) for the latest status. From 37cc879b6883163a51f99b57d7a51bcaa4710e60 Mon Sep 17 00:00:00 2001 From: yomna Date: Mon, 30 Mar 2026 13:10:42 -0400 Subject: [PATCH 9/9] [Workers] Remove accidentally committed preview-builds.mdx --- .../workers/ci-cd/builds/preview-builds.mdx | 155 ------------------ 1 file changed, 155 deletions(-) delete mode 100644 src/content/docs/workers/ci-cd/builds/preview-builds.mdx diff --git a/src/content/docs/workers/ci-cd/builds/preview-builds.mdx b/src/content/docs/workers/ci-cd/builds/preview-builds.mdx deleted file mode 100644 index f2dd02fa9ab..00000000000 --- a/src/content/docs/workers/ci-cd/builds/preview-builds.mdx +++ /dev/null @@ -1,155 +0,0 @@ ---- -pcx_content_type: concept -title: Preview builds -description: Understand how Workers Builds creates isolated preview environments for feature branches using Worker Previews. -sidebar: - order: 7 ---- - -import { Render, Tabs, TabItem } from "~/components"; - -When you enable non-production branch builds, every push to a feature branch creates an isolated **Worker Preview** — a fully functional copy of your Worker with its own bindings, environment variables, secrets, and URL. This lets your team test changes in a production-like environment without affecting live traffic or production data. - -## How preview builds work - -When you push to a non-production branch: - -1. Workers Builds detects the push event from your connected Git repository. -2. A build runs your configured build command (for example, `npm run build`). -3. The build system creates a **Worker Preview** — an isolated child Worker named after your branch. -4. Your code is deployed to the Preview with its own set of bindings and secrets. -5. A PR/MR comment is posted with the preview URL. - -The preview URL follows the format: - -``` -https://-..workers.dev -``` - -Each subsequent push to the same branch updates the existing Preview with a new deployment. The preview URL stays stable — it always points to the latest deployment on that branch. - -:::note -Worker Previews are different from [Preview URLs](/workers/configuration/previews/). Preview URLs generate a versioned URL for each Worker version but share production bindings. Worker Previews create fully isolated environments with their own configuration. -::: - -## What changes for existing Builds users - -If you have been using non-production branch builds with the default `wrangler versions upload` command, enabling Worker Previews upgrades your branch preview experience: - -| | Before (Preview URLs) | After (Worker Previews) | -|---|---|---| -| **What gets created** | A versioned URL pointing to your production Worker | An isolated child Worker with its own environment | -| **Bindings and secrets** | Same as production | Configured separately via Preview Defaults | -| **Branch URL** | `-..workers.dev` | `-..workers.dev` | -| **Commit URL** | `-..workers.dev` | `-..workers.dev` | -| **Observability** | Shares production settings | Independently configurable | -| **PR comments** | Shows branch and commit preview URLs | Shows Preview URL and deployment URL | - -The branch preview URL format stays the same, so existing bookmarks and integrations continue to work. The key difference is that your preview now runs with its own isolated configuration instead of sharing production secrets and bindings. - -## Enable preview builds - -To enable preview builds with Worker Previews: - -1. Go to **Workers & Pages** > your Worker > **Settings** > **Build**. -2. Under **Branch control**, enable **Builds for non-production branches**. -3. Select **Enable preview builds**. This updates your non-production branch deploy command to use Worker Previews. - -Once enabled, your build configuration will show Worker Previews as active. Every push to a feature branch will create or update an isolated Preview environment. - -## Configure Preview Defaults - -Preview Defaults define the bindings, variables, secrets, and observability settings that every new Preview starts with. Configure these once, and all branch previews inherit them automatically. - -### From the dashboard - -1. Go to **Workers & Pages** > your Worker > **Settings**. -2. Switch between the **Production** and **Previews** tabs to configure each environment independently. -3. For each binding or variable, you can either use the production value or set a preview-specific value. - -For example, you might point your KV binding at a staging namespace for Previews while keeping production pointed at your live namespace. - -### From Wrangler - -Add a `previews` block to your `wrangler.json` to define preview-specific overrides: - -```json -{ - "name": "my-worker", - "vars": { - "ENVIRONMENT": "production", - "API_URL": "https://api.example.com" - }, - "kv_namespaces": [ - { "binding": "MY_KV", "id": "production-kv-id" } - ], - "previews": { - "vars": { - "ENVIRONMENT": "preview", - "API_URL": "https://api.staging.example.com" - }, - "kv_namespaces": [ - { "binding": "MY_KV", "id": "staging-kv-id" } - ] - } -} -``` - -Values in the `previews` block override the top-level values for Preview deployments. Any binding not specified in `previews` falls back to its Preview Default (configured in the dashboard) or is omitted. - -To sync your `wrangler.json` preview settings to the dashboard: - -```sh -npx wrangler preview settings update -``` - -### Keeping environments in sync - -When you add a new binding or variable to production, your Previews environment may fall out of sync. The dashboard will show an **Import** action on the Bindings or Settings tab when it detects missing configuration. Use this to copy new bindings from production into your Preview Defaults — you can choose to use the production value as-is or set a preview-specific value for each one. - -## Preview secrets - -Preview secrets are managed separately from production secrets. Add a secret that only Previews can access: - -```sh -npx wrangler preview secret put MY_SECRET -``` - -List all Preview secrets: - -```sh -npx wrangler preview secret list -``` - -Preview secrets are stored in Preview Defaults and inherited by all Previews. They never appear in production configuration. - -## View and manage Previews - -Active Previews appear in the **Previews** tab of your Worker in the dashboard. Each Preview shows: - -- The branch it was created from -- The stable preview URL -- Recent deployments -- Observability and settings - -You can also manage Previews from the CLI: - -```sh -# Delete a Preview and all its deployments -npx wrangler preview delete - -# Delete a specific Preview by name -npx wrangler preview delete --name feature-branch -``` - -## Automatic cleanup - -Previews can be configured to auto-delete when their tracking branch is deleted from the repository. This setting is available per-Preview in the dashboard under the Preview's **Settings** tab. - -Previews also have a maximum limit per Worker. When the limit is reached, the least recently deployed Preview is automatically removed. - -## Limitations - -- [Service bindings](/workers/runtime-apis/bindings/service-bindings/) in a Preview always target the **production** instance of the bound Worker. You cannot point a service binding at another Preview. -- Non-fetch handlers (Cron Triggers, Queue consumers, etc.) cannot be invoked directly on a Preview. To test these, call the handler from a fetch handler within your Preview. -- [Durable Object](/durable-objects/) isolation in Previews requires additional API-side support that is currently being rolled out. Check the [Worker Previews documentation](/workers/previews/) for the latest status.