订阅以接收新文章的通知:

Cloudflare Snippets are now Generally Available

2025-04-09

4 分钟阅读时间
这篇博文也有 English 版本。

Program your traffic at the edge — fast, flexible, and free

Cloudflare Snippets are now generally available (GA) for all paid plans, giving you a fast, flexible way to control HTTP traffic using lightweight JavaScript “code rules” — at no extra cost.

Need to transform headers dynamically, fine-tune caching, rewrite URLs, retry failed requests, replace expired links, throttle suspicious traffic, or validate authentication tokens? Snippets provide a production-ready solution built for performance, security, and control.

With GA, we’re introducing a new code editor to streamline writing and testing logic. This summer, we’re also rolling out an integration with Secrets Store — enabling you to bind and manage sensitive values like API keys directly in Snippets, securely and at scale.

What are Snippets?

Snippets bring the power of JavaScript to Cloudflare Rules, letting you write logic that runs before a request reaches your origin or after a response returns from upstream. They’re ideal when built-in rule actions aren’t quite enough. While Cloudflare Rules let you define traffic logic without code, Snippets extend that model with greater flexibility for advanced scenarios.

Think of Snippets as the ultra-fast “code layer” of Cloudflare Rules: the Ruleset Engine evaluates your rules and invokes your code, which then runs on the Workers runtime.

Key capabilities of Snippets:

Best of all? Snippets are included at no extra cost for Pro, Business, and Enterprise plans — with no usage-based fees.

The journey to GA: How Snippets became production-grade

Cloudflare Snippets started as a bold idea: bring the power of JavaScript-based logic to Cloudflare Rules, without the complexity of a full-stack developer platform.

Over the past two years, Snippets have evolved into a production-ready “code rules” solution, shaping the future of HTTP traffic control.

2022: Cloudflare Snippets were announced during Developer Week as a solution for users needing flexible HTTP traffic modifications without a full Worker.

2023: Alpha launch — hundreds of users tested Snippets for high-performance traffic logic.

2024: 7x traffic growth, processing 17,000 requests per second. Terraform support and production-grade backend were released.

2025: General Availability — Snippets introduces a new code editor, increased limits alongside other Cloudflare Rules products, integration with Trace, and a production-grade experience built for scale, handling over 2 million requests per second at peak. Integration with the Secrets Store is rolling out this summer.

New: Snippets + Trace

Cloudflare Trace now shows exactly which Snippets were triggered on a request. This makes it easier to debug traffic behavior, verify logic execution, and understand how your Snippets interact with other products in the request pipeline.

Whether you’re fine-tuning header logic or troubleshooting a routing issue, Trace gives you real-time insight into how your edge logic behaves in production.

Coming soon: Snippets + Secrets Store

In the third quarter, you’ll be able to securely access API keys, authentication tokens, and other sensitive values from Secrets Store directly in your Snippets. No more plaintext secrets in your code, no more workarounds.

Once rolled out, secrets can be configured for Snippets via the dashboard or API under the new “Settings” button.

When to use Snippets vs. Cloudflare Workers

Snippets are fast, flexible, and free, but how do they compare to Cloudflare Workers? Both allow you to programmatically control traffic. However, they solve different problems:

Feature

Snippets

Workers

Execute scripts based on request attributes (headers, geolocation, cookies, etc.)

Modify HTTP requests/responses or serve a different response

Add, remove, or rewrite headers dynamically

Cache assets at the edge

Route traffic dynamically between origins

Authenticate requests, pre-sign URLs, run A/B testing

Perform compute-intensive tasks (e.g., AI inference, image processing)

Store persistent data (e.g., KV, Durable Objects, D1)

Deploy via CLI (Wrangler)

Use TypeScript, Python, Rust or other programming languages

Use Snippets when:

  • You need ultra-fast conditional traffic modifications directly on Cloudflare’s network.

  • You want to extend Cloudflare Rules beyond built-in actions.

  • You need free, unlimited invocations within the execution limits.

  • You are migrating from VCL, Akamai’s EdgeWorkers, or on-premise logic.

Use Workers when:

  • Your application requires state management, Developer Platform product integrations, or high compute limits.

  • You are building APIs, full-stack applications, or complex workflows.

  • You need logging, debugging tools, CLI support, and gradual rollouts.

Still unsure? Check out our detailed guide for best practices.

Snippets in action: real-world use cases

Below are practical use cases demonstrating Snippets. Each script can be dynamically triggered using our powerful Rules language, so you can granularly control which requests your Snippets will be applied to.

1. Dynamically modify headers

Inject custom headers, remove unnecessary ones, and tweak values on the fly:

export default {
  async fetch(request) {
    const timestamp = Date.now().toString(16); // convert timestamp to HEX
    const modifiedRequest = new Request(request, { headers: new Headers(request.headers) });
    modifiedRequest.headers.set("X-Hex-Timestamp", timestamp); // send HEX timestamp to upstream

    const response = await fetch(modifiedRequest);
    const newResponse = new Response(response.body, response); // make response from upstream mutable

    newResponse.headers.append("x-snippets-hello", "Hello from Cloudflare Snippets"); // add new response header
    newResponse.headers.delete("x-header-to-delete"); // delete response header
    newResponse.headers.set("x-header-to-change", "NewValue"); // replace the value of existing response header

    return newResponse;
  },
};

2. Serve a custom maintenance page

Route traffic to a maintenance page when your origin is undergoing planned maintenance:

export default {
    async fetch(request) { // for all matching requests, return predefined HTML response with 503 status code
        return new Response(`
            <!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="UTF-8">
                <title>We'll Be Right Back!</title>
                <style> body { font-family: Arial, sans-serif; text-align: center; padding: 20px; } </style>
            </head>
            <body>
                <h1>We'll Be Right Back!</h1>
                <p>Our site is undergoing maintenance. Check back soon!</p>
            </body>
            </html>
        `, { status: 503, headers: { "Content-Type": "text/html" } });
    }
};

3. Retry failed requests to a backup origin

Ensure reliability by automatically rerouting requests when your primary origin returns an unexpected response:

export default {
  async fetch(request) {
    const response = await fetch(request); // send original request to the origin

    if (!response.ok && !response.redirected) { // if response is not 200 OK or a redirect, send to another origin
      const newRequest = new Request(request); // clone the original request to construct a new request
      newRequest.headers.set("X-Rerouted", "1"); // add a header to identify a re-routed request at the new origin
      const url = new URL(request.url); // clone the original URL
      url.hostname = "backup.example.com"; // send request to a different origin / hostname
      return await fetch(url, newRequest); // serve response from the backup origin
    }

    return response; // otherwise, serve response from the primary origin
  },
};

4. Redirect users based on their location

Send visitors to region-specific sites for better localization:

export default {
    async fetch(request) {
        const country = request.cf.country; // identify visitor's country using request.cf property
        const redirectMap = { US: "https://example.com/us", EU: "https://example.com/eu" }; // define redirects for each country
        if (redirectMap[country]) return Response.redirect(redirectMap[country], 301); // redirect on match
        return fetch(request); // otherwise, proceed to upstream normally
    }
};

Getting started with Snippets

Snippets are available right now in the Cloudflare dashboard under Rules > Snippets:

  1. Go to Rules → Snippets.

  2. Use prebuilt templates or write your own JavaScript code.

  3. Configure a flexible rule to trigger your Snippet.

  4. Test and deploy instantly.

  5. Automate via API or Terraform.

Try Snippets today

Cloudflare Snippets are now generally available, bringing fast, cost-free, and intelligent HTTP traffic control to all paid plans.

With native integration into Cloudflare Rules and Terraform — and Secrets Store integration coming this summer — Snippets provide the most efficient way to manage advanced traffic logic at scale.

Explore Snippets in the Cloudflare Dashboard and start optimizing your traffic with lightweight, flexible rules that enhance performance and reduce complexity.

我们保护整个企业网络,帮助客户高效构建互联网规模的应用程序,加速任何网站或互联网应用程序抵御 DDoS 攻击,防止黑客入侵,并能协助您实现 Zero Trust 的过程

从任何设备访问 1.1.1.1,以开始使用我们的免费应用程序,帮助您更快、更安全地访问互联网。要进一步了解我们帮助构建更美好互联网的使命,请从这里开始。如果您正在寻找新的职业方向,请查看我们的空缺职位
Developer WeekSnippets普遍可用JavaScriptCDNEdge Rules开发人员

在 X 上关注

Cloudflare|@cloudflare

相关帖子