Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Comprehensive Cloudflare platform skill covering Workers, D1, R2, KV, AI, Durable Objects, and security.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
references/snippets/configuration.md
1# Snippets Configuration Guide23## Configuration Methods45### 1. Dashboard (GUI)6**Best for**: Quick tests, single snippets, visual rule building78```91. Go to zone → Rules → Snippets102. Click "Create Snippet" or select template113. Enter snippet name (a-z, 0-9, _ only, cannot change later)124. Write JavaScript code (32KB max)135. Configure snippet rule:14- Expression Builder (visual) or Expression Editor (text)15- Use Ruleset Engine filter expressions166. Test with Preview/HTTP tabs177. Deploy or Save as Draft18```1920### 2. REST API21**Best for**: CI/CD, automation, programmatic management2223```bash24# Create/update snippet25curl "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/snippets/$SNIPPET_NAME" \26--request PUT \27--header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \28--form "[email protected]" \29--form "metadata={\"main_module\": \"example.js\"}"3031# Create snippet rule32curl "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/snippets/snippet_rules" \33--request PUT \34--header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \35--header "Content-Type: application/json" \36--data '{37"rules": [38{39"description": "Trigger snippet on /api paths",40"enabled": true,41"expression": "starts_with(http.request.uri.path, \"/api/\")",42"snippet_name": "api_snippet"43}44]45}'4647# List snippets48curl "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/snippets" \49--header "Authorization: Bearer $CLOUDFLARE_API_TOKEN"5051# Delete snippet52curl "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/snippets/$SNIPPET_NAME" \53--request DELETE \54--header "Authorization: Bearer $CLOUDFLARE_API_TOKEN"55```5657### 3. Terraform58**Best for**: Infrastructure-as-code, multi-zone deployments5960```hcl61# Configure Terraform provider62terraform {63required_providers {64cloudflare = {65source = "cloudflare/cloudflare"66version = "~> 4.0"67}68}69}7071provider "cloudflare" {72api_token = var.cloudflare_api_token73}7475# Create snippet76resource "cloudflare_snippet" "security_headers" {77zone_id = var.zone_id78name = "security_headers"7980main_module = "security_headers.js"81files {82name = "security_headers.js"83content = file("${path.module}/snippets/security_headers.js")84}85}8687# Create snippet rule88resource "cloudflare_snippet_rules" "security_rules" {89zone_id = var.zone_id9091rules {92description = "Apply security headers to all requests"93enabled = true94expression = "true"95snippet_name = cloudflare_snippet.security_headers.name96}97}98```99100### 4. Pulumi101**Best for**: Multi-cloud IaC, TypeScript/Python/Go workflows102103```typescript104import * as cloudflare from "@pulumi/cloudflare";105import * as fs from "fs";106107// Create snippet108const securitySnippet = new cloudflare.Snippet("security-headers", {109zoneId: zoneId,110name: "security_headers",111mainModule: "security_headers.js",112files: [{113name: "security_headers.js",114content: fs.readFileSync("./snippets/security_headers.js", "utf8"),115}],116});117118// Create snippet rule119const snippetRule = new cloudflare.SnippetRules("security-rules", {120zoneId: zoneId,121rules: [{122description: "Apply security headers",123enabled: true,124expression: "true",125snippetName: securitySnippet.name,126}],127});128```129130## Filter Expressions131132Snippets use Cloudflare's Ruleset Engine expression language to determine when to execute.133134### Common Expression Patterns135136```javascript137// Host matching138http.host eq "example.com"139http.host in {"example.com" "www.example.com"}140http.host contains "example"141142// Path matching143http.request.uri.path eq "/api/users"144starts_with(http.request.uri.path, "/api/")145ends_with(http.request.uri.path, ".json")146matches(http.request.uri.path, "^/api/v[0-9]+/")147148// Query parameters149http.request.uri.query contains "debug=true"150151// Headers152http.headers["user-agent"] contains "Mobile"153http.headers["accept-language"] eq "en-US"154155// Cookies156http.cookie contains "session="157158// Geolocation159ip.geoip.country eq "US"160ip.geoip.continent eq "EU"161162// Bot detection (requires Bot Management)163cf.bot_management.score lt 30164165// Method166http.request.method eq "POST"167http.request.method in {"POST" "PUT" "PATCH"}168169// Combine with logical operators170http.host eq "example.com" and starts_with(http.request.uri.path, "/api/")171ip.geoip.country eq "US" or ip.geoip.country eq "CA"172not http.headers["user-agent"] contains "bot"173```174175### Expression Functions176177| Function | Example | Description |178|----------|---------|-------------|179| `starts_with()` | `starts_with(http.request.uri.path, "/api/")` | Check prefix |180| `ends_with()` | `ends_with(http.request.uri.path, ".json")` | Check suffix |181| `contains()` | `contains(http.headers["user-agent"], "Mobile")` | Check substring |182| `matches()` | `matches(http.request.uri.path, "^/api/")` | Regex match |183| `lower()` | `lower(http.host) eq "example.com"` | Convert to lowercase |184| `upper()` | `upper(http.headers["x-api-key"])` | Convert to uppercase |185| `len()` | `len(http.request.uri.path) gt 100` | String length |186187## Deployment Workflow188189### Development1901. Write snippet code locally1912. Test syntax with `node snippet.js` or TypeScript compiler1923. Deploy to Dashboard or use API with `Save as Draft`1934. Test with Preview/HTTP tabs in Dashboard1945. Enable rule when ready195196### Production1971. Store snippet code in version control1982. Use Terraform/Pulumi for reproducible deployments1993. Deploy to staging zone first2004. Test with real traffic (use low-traffic subdomain)2015. Apply to production zone2026. Monitor with Analytics/Logpush203204## Limits & Requirements205206| Resource | Limit | Notes |207|----------|-------|-------|208| Snippet size | 32 KB | Per snippet, compressed |209| Snippet name | 64 chars | `a-z`, `0-9`, `_` only, immutable |210| Snippets per zone | 20 | Soft limit, contact support for more |211| Rules per zone | 20 | One rule per snippet typical |212| Expression length | 4096 chars | Per rule expression |213214## Authentication215216### API Token (Recommended)217```bash218# Create token at: https://dash.cloudflare.com/profile/api-tokens219# Required permissions: Zone.Snippets:Edit, Zone.Rules:Edit220export CLOUDFLARE_API_TOKEN="your_token_here"221```222223### API Key (Legacy)224```bash225export CLOUDFLARE_EMAIL="[email protected]"226export CLOUDFLARE_API_KEY="your_global_api_key"227```