Cache using fetch·续

Override based on origin response code

// Force response to be cached for 86400 seconds for 200 status
// codes, 1 second for 404, and do not cache 500 errors.
fetch(request, {
    cf: { cacheTtlByStatus: { "200-299": 86400, 404: 1, "500-599": 0 } },
});

This option is a version of the cacheTtl feature which chooses a TTL based on the response's status code and does not automatically set cacheEverything: true. If the response to this request has a status code that matches, Cloudflare will cache for the instructed time, and override cache directives sent by the origin. You can review details on the cacheTtl feature on the Request page.

Customize cache behavior based on request file type

Using custom cache keys and overrides based on response code, you can write a Worker that sets the TTL based on the response status code from origin, and request file type.

The following example demonstrates how you might use this to cache requests for streaming media assets:

index.jsjs

export default {
    async fetch(request) {
        // Instantiate new URL to make it mutable
        const newRequest = new URL(request.url);

const customCacheKey = `${newRequest.hostname}${newRequest.pathname}`;
        const queryCacheKey = `${newRequest.hostname}${newRequest.pathname}${newRequest.search}`;

// Different asset types usually have different caching strategies. Most of the time media content such as audio, videos and images that are not user-generated content would not need to be updated often so a long TTL would be best. However, with HLS streaming, manifest files usually are set with short TTLs so that playback will not be affected, as this files contain the data that the player would need. By setting each caching strategy for categories of asset types in an object within an array, you can solve complex needs when it comes to media content for your application

const cacheAssets = [
            {
                asset: "video",
                key: customCacheKey,
                regex:
                    /(.*\/Video)|(.*\.(m4s|mp4|ts|avi|mpeg|mpg|mkv|bin|webm|vob|flv|m2ts|mts|3gp|m4v|wmv|qt))/,
                info: 0,
                ok: 31556952,
                redirects: 30,
                clientError: 10,
                serverError: 0,
            },
            {
                asset: "image",
                key: queryCacheKey,
                regex:
                    /(.*\/Images)|(.*\.(jpg|jpeg|png|bmp|pict|tif|tiff|webp|gif|heif|exif|bat|bpg|ppm|pgn|pbm|pnm))/,
                info: 0,
                ok: 3600,
                redirects: 30,
                clientError: 10,
                serverError: 0,
            },
            {
                asset: "frontEnd",
                key: queryCacheKey,
                regex: /^.*\.(css|js)/,
                info: 0,
                ok: 3600,
                redirects: 30,
                clientError: 10,
                serverError: 0,
            },
            {
                asset: "audio",
                key: customCacheKey,
                regex:
                    /(.*\/Audio)|(.*\.(flac|aac|mp3|alac|aiff|wav|ogg|aiff|opus|ape|wma|3gp))/,
                info: 0,
                ok: 31556952,
                redirects: 30,
                clientError: 10,
                serverError: 0,
            },
            {
                asset: "directPlay",
                key: customCacheKey,
                regex: /.*(\/Download)/,
                info: 0,
                ok: 31556952,
                redirects: 30,
                clientError: 10,
                serverError: 0,
            },
            {
                asset: "manifest",
                key: customCacheKey,
                regex: /^.*\.(m3u8|mpd)/,
                info: 0,
                ok: 3,
                redirects: 2,
                clientError: 1,
                serverError: 0,
            },
        ];

const { asset, regex, ...cache } =
            cacheAssets.find(({ regex }) => newRequest.pathname.match(regex)) ?? {};

const newResponse = await fetch(request, {
            cf: {
                cacheKey: cache.key,
                polish: false,
                cacheEverything: true,
                cacheTtlByStatus: {
                    "100-199": cache.info,
                    "200-299": cache.ok,
                    "300-399": cache.redirects,
                    "400-499": cache.clientError,
                    "500-599": cache.serverError,
                },
                cacheTags: ["static"],
            },
        });

const response = new Response(newResponse.body, newResponse);

// For debugging purposes
        response.headers.set("debug", JSON.stringify(cache));
        return response;
    },
};

Service Workers are deprecated

Service Workers are deprecated, but still supported. We recommend using Module Workers instead. New features may not be supported for Service Workers.

index.jsjs

addEventListener("fetch", (event) => {
    return event.respondWith(handleRequest(event.request));
});

async function handleRequest(request) {
    // Instantiate new URL to make it mutable
    const newRequest = new URL(request.url);

// Set `const` to be used in the array later on
    const customCacheKey = `${newRequest.hostname}${newRequest.pathname}`;
    const queryCacheKey = `${newRequest.hostname}${newRequest.pathname}${newRequest.search}`;

// Set all variables needed to manipulate Cloudflare's cache using the fetch API in the `cf` object. You will be passing these variables in the objects down below.
    const cacheAssets = [
        {
            asset: "video",
            key: customCacheKey,
            regex:
                /(.*\/Video)|(.*\.(m4s|mp4|ts|avi|mpeg|mpg|mkv|bin|webm|vob|flv|m2ts|mts|3gp|m4v|wmv|qt))/,
            info: 0,
            ok: 31556952,
            redirects: 30,
            clientError: 10,
            serverError: 0,
        },
        {
            asset: "image",
            key: queryCacheKey,
            regex:
                /(.*\/Images)|(.*\.(jpg|jpeg|png|bmp|pict|tif|tiff|webp|gif|heif|exif|bat|bpg|ppm|pgn|pbm|pnm))/,
            info: 0,
            ok: 3600,
            redirects: 30,
            clientError: 10,
            serverError: 0,
        },
        {
            asset: "frontEnd",
            key: queryCacheKey,
            regex: /^.*\.(css|js)/,
            info: 0,
            ok: 3600,
            redirects: 30,
            clientError: 10,
            serverError: 0,
        },
        {
            asset: "audio",
            key: customCacheKey,
            regex:
                /(.*\/Audio)|(.*\.(flac|aac|mp3|alac|aiff|wav|ogg|aiff|opus|ape|wma|3gp))/,
            info: 0,
            ok: 31556952,
            redirects: 30,
            clientError: 10,
            serverError: 0,
        },
        {
            asset: "directPlay",
            key: customCacheKey,
            regex: /.*(\/Download)/,
            info: 0,
            ok: 31556952,
            redirects: 30,
            clientError: 10,
            serverError: 0,
        },
        {
            asset: "manifest",
            key: customCacheKey,
            regex: /^.*\.(m3u8|mpd)/,
            info: 0,
            ok: 3,
            redirects: 2,
            clientError: 1,
            serverError: 0,
        },
    ];

// the `.find` method is used to find elements in an array (`cacheAssets`), in this case, `regex`, which can passed to the .`match` method to match on file extensions to cache, since they are many media types in the array. If you want to add more types, update the array. Refer to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find for more information.
    const { asset, regex, ...cache } =
        cacheAssets.find(({ regex }) => newRequest.pathname.match(regex)) ?? {};

const newResponse = await fetch(request, {
        cf: {
            cacheKey: cache.key,
            polish: false,
            cacheEverything: true,
            cacheTtlByStatus: {
                "100-199": cache.info,
                "200-299": cache.ok,
                "300-399": cache.redirects,
                "400-499": cache.clientError,
                "500-599": cache.serverError,
            },
            cacheTags: ["static"],
        },
    });

const response = new Response(newResponse.body, newResponse);

// For debugging purposes
    response.headers.set("debug", JSON.stringify(cache));
    return response;
}

Using the HTTP Cache API

The cache mode can be set in fetch options. Currently Workers only support the no-store and no-cache mode for controlling the cache. When no-store is supplied the cache is bypassed on the way to the origin and the request is not cacheable. When no-cache is supplied the cache is forced to revalidate the currently cached response with the origin.

fetch(request, { cache: 'no-store'});
fetch(request, { cache: 'no-cache'});

Was this helpful?

YesNo

On this page

Cache using fetch·续 - 图1Docs

{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/workers/examples/cache-using-fetch/#page","headline":"Cache using fetch","description":"Determine how to cache a resource by setting TTLs, custom cache keys, and cache headers in a fetch request.","url":"https://developers.cloudflare.com/workers/examples/cache-using-fetch/","inLanguage":"en","image":"https://developers.cloudflare.com/workers/examples/cache-using-fetch/og.png?v=7d6169fe1dc8b2ed","dateModified":"2026-07-06","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"},"keywords":["Caching","Middleware","JavaScript","TypeScript","Python","Rust"]}


description: Return a response based on the incoming request's URL, HTTP method, User Agent, IP address, ASN or device type. title: Conditional response image: https://developers.cloudflare.com/workers/examples/conditional-response/og.png?v=54f6a0f165a69838


Skip to content

Documentation Index
Fetch the complete documentation index at: https://developers.cloudflare.com/workers/llms.txt
Use this file to discover all available pages before exploring further.