Skip to content

Configure via API

You can create Snippets using the Cloudflare API.

Required permissions

The API token used in API requests to manage Snippets must have at least the following permission:

  • Zone > Snippets > Edit

Endpoints

To obtain the complete endpoint, append the Snippets endpoints listed below to the Cloudflare API base URL:

https://api.cloudflare.com/client/v4

The {zone_id} argument is the zone ID (a hexadecimal string). You can find this value in the Cloudflare dashboard.

The following table summarizes the available operations.

OperationVerb + Endpoint
List all code snippetsGET /zones/{zone_id}/snippets
Create/update code snippetPUT /zones/{zone_id}/snippets/{snippet_name}
Delete code snippetDELETE /zones/{zone_id}/snippets/{snippet_name}
List snippet rulesGET /zones/{zone_id}/snippets/snippet_rules
Create/update/delete snippet rulesPUT /zones/{zone_id}/snippets/snippet_rules

Example API calls

Create/update code snippet

To create or update a Snippet, use the following PUT request. The snippet is named {snippet_name} and the body contains the JavaScript code.

Terminal window
curl --request PUT https://api.cloudflare.com/client/v4/zones/{zone_id}/snippets/{snippet_name} \
--header "Authorization: Bearer <API_TOKEN>" \
--header "Content-Type: multipart/form-data" \
--form files=@example.js \
--form metadata='{"main_module":"example.js"}'

The required body parameters are:

  • files: The file with your JavaScript code.
  • metadata: Object containing main_module, which must match the filename of the uploaded file.

To make this example work, save your JavaScript code in a file named example.js, and then execute curl command with a PUT request from the folder where example.js is located.

Example response
{
"errors": [],
"messages": [],
"success": true,
"result": {
"created_on": "2023-07-24-00:00:00",
"modified_on": "2023-07-24-00:00:00",
"snippet_name": "snippet_name_01"
}
}

Create/update/delete snippet rules

Once you have created a code snippet, you can link it to rules. This is done via the following PUT request to the snippet_rules endpoint.

Terminal window
curl --request PUT \
"https://api.cloudflare.com/client/v4/zones/{zone_id}/snippets/snippet_rules" \
--header "Authorization: Bearer <API_TOKEN>" \
--header "Content-Type: application/json" \
--data '{
"rules": [
{
"description": "Trigger snippet on specific cookie",
"enabled": true,
"expression": "http.cookie eq \"a=b\"",
"snippet_name": "snippet_name_01"
}
]
}'