Skip to content

Cloudflare.Snippets reference

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.

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 });
},
};
`,
});
yield* Cloudflare.Snippets.SnippetRules("Rules", {
zoneId: zone.zoneId,
rules: [
{
snippetName: snippet.name,
expression: 'http.request.uri.path wildcard "/api/*"',
},
],
});

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.

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",
},
],
});