Cloudflare.Snippets reference
Snippet
Section titled “Snippet”Source:
src/Cloudflare/Snippets/Snippet.ts
A Cloudflare Snippet — a lightweight JavaScript module that runs on Cloudflare’s edge to modify HTTP traffic for a zone.
Uploading a snippet does not activate it: traffic only flows through a
snippet once a SnippetRules rule references it with a matching
expression.
Safety: snippets carry no ownership markers. When there is no prior
state, read looks the snippet up by name and reports an existing match
as Unowned, so the engine refuses to take it over unless --adopt
(or adopt(true)) is set.
Snippet: Creating a Snippet
Section titled “Snippet: Creating a Snippet”const snippet = yield* Cloudflare.Snippets.Snippet("HeaderSnippet", { zoneId: zone.zoneId, code: ` export default { async fetch(request) { const response = await fetch(request); const headers = new Headers(response.headers); headers.set("x-snippet", "hello"); return new Response(response.body, { ...response, headers }); }, }; `,});Snippet: Activating with Snippet Rules
Section titled “Snippet: Activating with Snippet Rules”yield* Cloudflare.Snippets.SnippetRules("Rules", { zoneId: zone.zoneId, rules: [ { snippetName: snippet.name, expression: 'http.request.uri.path wildcard "/api/*"', }, ],});SnippetRules
Section titled “SnippetRules”Source:
src/Cloudflare/Snippets/SnippetRules.ts
The ordered list of snippet rules for a Cloudflare zone.
Snippet rules activate snippets against traffic: each rule pairs a
Rules-language expression with the name of the snippet to execute on
matching requests. The zone has exactly one rule list — this resource
owns it in its entirety (PUT-replace semantics), so there should be at
most one SnippetRules resource per zone.
Safety: when there is no prior state and the zone already has a
non-empty rule list, read reports it as Unowned and the engine
refuses to take it over unless --adopt (or adopt(true)) is set.
SnippetRules: Activating Snippets
Section titled “SnippetRules: Activating Snippets”const snippet = yield* Cloudflare.Snippets.Snippet("HeaderSnippet", { zoneId: zone.zoneId, code: snippetCode,});
yield* Cloudflare.Snippets.SnippetRules("Rules", { zoneId: zone.zoneId, rules: [ { snippetName: snippet.name, expression: 'http.request.uri.path wildcard "/api/*"', description: "add headers to API responses", }, ],});