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 {@link 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.
Creating a Snippet
Section titled “Creating a Snippet”const snippet = yield* Cloudflare.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 }); }, }; `,});Activating with Snippet Rules
Section titled “Activating with Snippet Rules”yield* Cloudflare.SnippetRules("Rules", { zoneId: zone.zoneId, rules: [ { snippetName: snippet.name, expression: 'http.request.uri.path wildcard "/api/*"', }, ],});