Skip to main content

Cache

Model-written

contextmethodsetupresultanalysislimitation

Background

Cache API enables fine-grained cache read/write on Cloudflare

The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache.The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache.Cache API allows fine-grained control of Cloudflare cache It provides programmatic read/write access to the global network cacheCache API allows fine-grained control of Cloudflare cacheCache API

Note

The Cache API is a programmatic interface for reading from and writing to Cloudflare's cache from inside a Worker. To cache responses from your Worker so that Cloudflare returns them without executing your Worker, use Workers Caching instead. The two mechanisms are independent.The Cache API is a programmatic interface for reading from and writing to Cloudflare's cache from inside a Worker. To cache responses from your Worker so that Cloudflare returns them without executing your Worker, use Workers Caching instead.Cache API is a programmatic cache interface inside Workers To return cached responses without executing the Worker, use Workers Caching instead, as the two are independentCache API is a programmatic cache interface inside WorkersCache API

The Cache API is available globally but the contents of the cache do not replicate outside of the originating data center. A GET /users response can be cached in the originating data center, but will not exist in another data center unless it has been explicitly created.The Cache API is available globally but the contents of the cache do not replicate outside of the originating data center. A GET /users response can be cached in the originating data center, but will not exist in another data center unless it has been explicitly created.Cache contents do not replicate across data centers A response cached in one data center will not exist in another unless explicitly created thereCache contents do not replicate across data centersCache contents

Tiered caching

The cache.put method is not compatible with tiered caching. Refer to Cache API for more information. To perform tiered caching, use the fetch API.The cache.put method is not compatible with tiered caching. To perform tiered caching, use the fetch API.cache.put is not compatible with tiered caching For tiered caching, the fetch API must be used insteadcache.put is not compatible with tiered cachingcache.put

Workers deployed to custom domains have access to functional cache operations. So do Pages functions, whether attached to custom domains or *.pages.dev domains.Workers deployed to custom domains have access to functional cache operations. So do Pages functions, whether attached to custom domains or *.pages.dev domains.Workers on custom domains and Pages functions have cache access This includes Pages functions attached to custom domains or *.pages.dev domainsWorkers on custom domains and Pages functions have cache accesscustom domains

However, any Cache API operations in the Cloudflare Workers dashboard editor and Playground previews will have no impact. For Workers fronted by Cloudflare Access, the Cache API is not currently available.However, any Cache API operations in the Cloudflare Workers dashboard editor and Playground previews will have no impact. For Workers fronted by Cloudflare Access, the Cache API is not currently available.Cache operations do nothing in dashboard editor and Playground previews Also, the Cache API is currently unavailable for Workers fronted by Cloudflare AccessCache operations do nothing in dashboard editor and Playground previewsCache operations

Note

This individualized zone cache object differs from Cloudflare’s Global CDN. For details, refer to How the cache works.This individualized zone cache object differs from Cloudflare’s Global CDN. For details, refer to How the cache works.Worker's individualized zone cache differs from Global CDN Details on the distinction are in How the cache worksWorker's individualized zone cache differs from Global CDNzone cache


Accessing Cache

Access the global cache via caches.default or caches.open

The caches.default API is strongly influenced by the web browsers’ Cache API, but there are some important differences. For instance, Cloudflare Workers runtime exposes a single global cache object.The caches.default API is strongly influenced by the web browsers’ Cache API, but there are some important differences. For instance, Cloudflare Workers runtime exposes a single global cache object.caches.default gives a single global cache object in Workers It resembles browser Cache API but differs, notably by exposing only one global cachecaches.default gives a single global cache object in Workerscaches.default

let cache = caches.default;
await cache.match(request);

You may create and manage additional Cache instances via the caches.open method.You may create and manage additional Cache instances via the caches.open method.Create extra Cache instances via caches.open This allows managing additional named caches beyond the defaultCreate extra Cache instances via caches.opencaches.open

let myCache = await caches.open('custom:cache');
await myCache.match(request);

Headers

Cache API honors Cache-Control, Cache-Tag, ETag, Expires, Last-Modified

Our implementation of the Cache API respects the following HTTP headers on the response passed to put():Our implementation of the Cache API respects the following HTTP headers on the response passed to put():Cache API respects specific HTTP response headers on put The headers listed control caching directives and validationCache API respects specific HTTP response headers on putHTTP response headers

  • Cache-Control
    • Controls caching directives. This is consistent with Cloudflare Cache-Control Directives. Refer to Edge TTL for a list of HTTP response codes and their TTL when Cache-Control directives are not present.
      Controls caching directives. Refer to Edge TTL for a list of HTTP response codes and their TTL when Cache-Control directives are not present.
      Cache-Control controls caching directives per Cloudflare rules When directives are absent, Edge TTL defines TTL per response code
      Cache-Control controls caching directives per Cloudflare rules
      Cache-Control
  • Cache-Tag
    • Allows resource purging by tag(s) later.
      Allows resource purging by tag(s) later.
      Cache-Tag enables later resource purging by tag Tagged resources can be purged selectively
      Cache-Tag enables later resource purging by tag
      Cache-Tag
  • ETag
    • Allows cache.match() to evaluate conditional requests with If-None-Match.
      Allows cache.match() to evaluate conditional requests with If-None-Match.
      ETag enables conditional requests in cache.match It is used to evaluate If-None-Match headers
      ETag enables conditional requests in cache.match
      ETag
  • Expires string
    • A string that specifies when the resource becomes invalid.
      A string that specifies when the resource becomes invalid.
      Expires specifies when the resource becomes invalid It controls expiration time for cached resources
      Expires specifies when the resource becomes invalid
      Expires
  • Last-Modified
    • Allows cache.match() to evaluate conditional requests with If-Modified-Since.
      Allows cache.match() to evaluate conditional requests with If-Modified-Since.
      Last-Modified enables conditional requests in cache.match It is used to evaluate If-Modified-Since headers
      Last-Modified enables conditional requests in cache.match
      Last-Modified

This differs from the web browser Cache API as they do not honor any headers on the request or response.This differs from the web browser Cache API as they do not honor any headers on the request or response.Cache API honors headers, unlike browser Cache API The browser Cache API does not honor request or response headersCache API honors headers, unlike browser Cache APIbrowser Cache API

Note

Responses with Set-Cookie headers are never cached, because this sometimes indicates that the response contains unique data. To store a response with a Set-Cookie header, either delete that header or set Cache-Control: private=Set-Cookie on the response before calling cache.put().Responses with Set-Cookie headers are never cached, because this sometimes indicates that the response contains unique data. To store a response with a Set-Cookie header, either delete that header or set Cache-Control: private=Set-Cookie on the response before calling cache.put().Responses with Set-Cookie are never cached by default This indicates unique data; delete the header or set Cache-Control: private=Set-Cookie to store itResponses with Set-Cookie are never cached by defaultSet-Cookie

Use the Cache-Control method to store the response without the Set-Cookie header.Use the Cache-Control method to store the response without the Set-Cookie header.Use Cache-Control to store without the Set-Cookie header This prevents caching the unique data indicated by Set-CookieUse Cache-Control to store without the Set-Cookie headerCache-Control


Methods

Put

cache.put stores a response under a request key, returning undefined

cache.put(request, response);
  • put(request, response) : Promise

    • Attempts to add a response to the cache, using the given request as the key. Returns a promise that resolves to undefined regardless of whether the cache successfully stored the response.
      Attempts to add a response to the cache, using the given request as the key. Returns a promise that resolves to undefined regardless of whether the cache successfully stored the response.
      put adds a response to cache and resolves to undefined It uses the request as key and returns undefined regardless of whether storage succeeded
      put adds a response to cache and resolves to undefined
      put

Note

The stale-while-revalidate and stale-if-error directives are not supported when using the cache.put or cache.match methods.The stale-while-revalidate and stale-if-error directives are not supported when using the cache.put or cache.match methods.stale-while-revalidate and stale-if-error are unsupported in put and match These directives cannot be used with cache.put or cache.matchstale-while-revalidate and stale-if-error are unsupported in put and matchstale-while-revalidate

Parameters

put takes a request key and a response to store

  • request string | Request

    • Either a string or a Request object to serve as the key. If a string is passed, it is interpreted as the URL for a new Request object.
      Either a string or a Request object to serve as the key. If a string is passed, it is interpreted as the URL for a new Request object.
      put request parameter accepts a string or Request object A string is interpreted as the URL for a new Request object
      put request parameter accepts a string or Request object
      request
  • response Response

    • A Response object to store under the given key.
      A Response object to store under the given key.
      put response parameter is a Response object to store It is stored under the provided request key
      put response parameter is a Response object to store
      Response

Invalid parameters

put rejects non-GET requests, 206 responses, and Vary: *

cache.put will throw an error if:cache.put will throw an error if:cache.put throws errors under specific conditions The list that follows details when an error is throwncache.put throws errors under specific conditionscache.put

  • The request passed is a method other than GET.
    The request passed is a method other than GET.
    cache.put throws if request method is not GET Only GET requests are allowed as cache keys
    cache.put throws if request method is not GET
    cache.put
  • The response passed has a status of 206 Partial Content.
    The response passed has a status of 206 Partial Content.
    cache.put throws on 206 Partial Content responses Responses with status 206 cannot be cached
    cache.put throws on 206 Partial Content responses
    cache.put
  • The response passed contains the header Vary: *. The value of the Vary header is an asterisk (*). Refer to the Cache API specification for more information.
    The response passed contains the header Vary: *. The value of the Vary header is an asterisk (*).
    cache.put throws if response has Vary: * An asterisk in the Vary header value is not allowed
    cache.put throws if response has Vary: *
    Vary: *

Errors

put returns 413 on uncacheable or too-large responses

cache.put returns a 413 error if Cache-Control instructs not to cache or if the response is too large.cache.put returns a 413 error if Cache-Control instructs not to cache or if the response is too large.cache.put returns 413 if not cacheable or too large This occurs when Cache-Control forbids caching or the response exceeds size limitscache.put returns 413 if not cacheable or too largecache.put

Note

cache.put will silently reject a 301 or 302 redirect response if both of the following are true:cache.put will silently reject a 301 or 302 redirect response if both of the following are true:cache.put silently rejects 301/302 redirects under conditions Both the cache key must omit query string and Location must contain itcache.put silently rejects 301/302 redirects under conditionscache.put

  1. The cache key does not include the query string (for example, a custom cache key set via Workers or Page Rules that strips the query string).
    The cache key does not include the query string (for example, a custom cache key set via Workers or Page Rules that strips the query string).
    Cache key without query string triggers silent redirect rejection This includes custom cache keys set via Workers or Page Rules that strip the query string
    Cache key without query string triggers silent redirect rejection
    Cache key
  2. The Location header in the redirect response contains the request's query string.
    The Location header in the redirect response contains the request's query string.
    Redirect Location containing query string triggers silent rejection If the Location header includes the request's query string along with a key lacking it, the redirect is silently rejected
    Redirect Location containing query string triggers silent rejection
    Location

This is a cache-poisoning mitigation. To cache redirect responses with query strings, either include the query string in your cache key, or remove the query string from the Location header before calling cache.put(). This restriction does not apply on .workers.dev domains, which include the query string in the cache key by default.This is a cache-poisoning mitigation. To cache redirect responses with query strings, either include the query string in your cache key, or remove the query string from the Location header before calling cache.put(). This restriction does not apply on .workers.dev domains, which include the query string in the cache key by default.Silent rejection of redirects is a cache-poisoning mitigation To cache them, include query string in key or remove it from Location; .workers.dev domains are exemptSilent rejection of redirects is a cache-poisoning mitigationcache-poisoning mitigation

Match

cache.match returns the cached response keyed to the request

cache.match(request, options);
  • match(request, options) : Promise<Response | undefined>

    • Returns a promise wrapping the response object keyed to that request.
      Returns a promise wrapping the response object keyed to that request.
      match returns a promise wrapping the cached response The response is keyed to the given request
      match returns a promise wrapping the cached response
      match

Note

The stale-while-revalidate and stale-if-error directives are not supported when using the cache.put or cache.match methods.The stale-while-revalidate and stale-if-error directives are not supported when using the cache.put or cache.match methods.stale-while-revalidate and stale-if-error unsupported in put and match These directives cannot be used with cache.put or cache.matchstale-while-revalidate and stale-if-error unsupported in put and matchstale-while-revalidate

Parameters

match accepts a request key and ignoreMethod option

  • request string | Request

    • The string or Request object used as the lookup key. Strings are interpreted as the URL for a new Request object.
      The string or Request object used as the lookup key. Strings are interpreted as the URL for a new Request object.
      match request parameter accepts a string or Request object Strings are interpreted as the URL for a new Request object
      match request parameter accepts a string or Request object
      request
  • options

    • Can contain one possible property: ignoreMethod (Boolean). When true, the request is considered to be a GET request regardless of its actual value.
      Can contain one possible property: ignoreMethod (Boolean). When true, the request is considered to be a GET request regardless of its actual value.
      match options include ignoreMethod boolean When true, the request is treated as GET regardless of its actual method
      match options include ignoreMethod boolean
      ignoreMethod

Unlike the browser Cache API, Cloudflare Workers do not support the ignoreSearch or ignoreVary options on match(). You can accomplish this behavior by removing query strings or HTTP headers at put() time.Unlike the browser Cache API, Cloudflare Workers do not support the ignoreSearch or ignoreVary options on match(). You can accomplish this behavior by removing query strings or HTTP headers at put() time.ignoreSearch and ignoreVary options are unsupported in match Equivalent behavior requires removing query strings or headers at put timeignoreSearch and ignoreVary options are unsupported in matchignoreSearch

Our implementation of the Cache API respects the following HTTP headers on the request passed to match():Our implementation of the Cache API respects the following HTTP headers on the request passed to match():Cache API respects specific HTTP request headers on match The headers listed affect range and conditional requestsCache API respects specific HTTP request headers on matchHTTP request headers

  • Range

    • Results in a 206 response if a matching response with a Content-Length header is found. Your Cloudflare cache always respects range requests, even if an Accept-Ranges header is on the response.
      Results in a 206 response if a matching response with a Content-Length header is found. Your Cloudflare cache always respects range requests, even if an Accept-Ranges header is on the response.
      Range header yields 206 if matching response has Content-Length Cloudflare cache always respects range requests, even with Accept-Ranges present
      Range header yields 206 if matching response has Content-Length
      Range
  • If-Modified-Since

    • Results in a 304 response if a matching response is found with a Last-Modified header with a value before the time specified in If-Modified-Since.
      Results in a 304 response if a matching response is found with a Last-Modified header with a value before the time specified in If-Modified-Since.
      If-Modified-Since yields 304 if Last-Modified is before specified time This enables conditional requests based on modification time
      If-Modified-Since yields 304 if Last-Modified is before specified time
      If-Modified-Since
  • If-None-Match

    • Results in a 304 response if a matching response is found with an ETag header with a value that matches a value in If-None-Match.
      Results in a 304 response if a matching response is found with an ETag header with a value that matches a value in If-None-Match.
      If-None-Match yields 304 if ETag matches This enables conditional requests based on entity tag
      If-None-Match yields 304 if ETag matches
      If-None-Match

Note

cache.match() never sends a subrequest to the origin. If no matching response is found in cache, the promise that cache.match() returns is fulfilled with undefined.cache.match() never sends a subrequest to the origin. If no matching response is found in cache, the promise that cache.match() returns is fulfilled with undefined.cache.match never sends a subrequest; returns undefined if missing If no matching response is found in cache, the promise resolves to undefinedcache.match never sends a subrequest; returns undefined if missingcache.match

Errors

match returns undefined on missing content; logs show 504

cache.match generates a 504 error response when the requested content is missing or expired. The Cache API does not expose this 504 directly to the Worker script, instead returning undefined. Nevertheless, the underlying 504 is still visible in Cloudflare Logs.cache.match generates a 504 error response when the requested content is missing or expired. The Cache API does not expose this 504 directly to the Worker script, instead returning undefined. Nevertheless, the underlying 504 is still visible in Cloudflare Logs.cache.match returns undefined on missing/expired content, logs show 504 The underlying 504 is not exposed to the Worker but remains visible in Cloudflare Logscache.match returns undefined on missing/expired content, logs show 504cache.match

If you use Cloudflare Logs, you may see these 504 responses with the RequestSource of edgeWorkerCacheAPI. Again, these are expected if the cached asset was missing or expired. Note that edgeWorkerCacheAPI requests are already filtered out in other views, such as Cache Analytics. To filter out these requests or to filter requests by end users of your website only, refer to Filter end users.If you use Cloudflare Logs, you may see these 504 responses with the RequestSource of edgeWorkerCacheAPI. Again, these are expected if the cached asset was missing or expired. Note that edgeWorkerCacheAPI requests are already filtered out in other views, such as Cache Analytics.504 responses with RequestSource edgeWorkerCacheAPI are expected in logs These indicate missing or expired cached assets and are filtered out in Cache Analytics504 responses with RequestSource edgeWorkerCacheAPI are expected in logsedgeWorkerCacheAPI

Delete

cache.delete removes a cached response, returning a boolean

cache.delete(request, options);
  • delete(request, options) : Promise<boolean>

Deletes the Response object from the cache and returns a Promise for a Boolean response:Deletes the Response object from the cache and returns a Promise for a Boolean response:delete removes a response from cache, returning a boolean promise The promise resolves to true if deleted and false if not presentdelete removes a response from cache, returning a boolean promisedelete

  • true: The response was cached but is now deleted
    true: The response was cached but is now deleted
    delete returns true when cached response is deleted This indicates the response was present and is now removed
    delete returns true when cached response is deleted
    delete
  • false: The response was not in the cache at the time of deletion.
    false: The response was not in the cache at the time of deletion.
    delete returns false when response was not cached This indicates the response was absent at deletion time
    delete returns false when response was not cached
    delete

Global purges

The cache.delete method only purges content of the cache in the data center that the Worker was invoked. For global purges, refer to Purging assets stored with the Cache API.The cache.delete method only purges content of the cache in the data center that the Worker was invoked. For global purges, refer to Purging assets stored with the Cache API.cache.delete purges only the invoking data center's cache For global purges, refer to Purging assets stored with the Cache APIcache.delete purges only the invoking data center's cachecache.delete

Parameters

delete takes a request key and ignoreMethod option

  • request string | Request

    • The string or Request object used as the lookup key. Strings are interpreted as the URL for a new Request object.
      The string or Request object used as the lookup key. Strings are interpreted as the URL for a new Request object.
      delete request parameter accepts a string or Request object Strings are interpreted as the URL for a new Request object
      delete request parameter accepts a string or Request object
      request
  • options object

    • Can contain one possible property: ignoreMethod (Boolean). Consider the request method a GET regardless of its actual value.
      Can contain one possible property: ignoreMethod (Boolean). Consider the request method a GET regardless of its actual value.
      delete options include ignoreMethod boolean When true, the request is considered a GET regardless of its actual method
      delete options include ignoreMethod boolean
      ignoreMethod