Edge Developer Platform
  • Edge Functions
    • Overview
    • Getting Started
    • Operation Guide
      • Function Management
      • Web Debugging
      • Function Trigger
      • Environment Variable
      • Code Replica
    • Runtime APIs
      • addEventListener
      • Cache
      • Cookies
      • Encoding
      • Fetch
      • FetchEvent
      • Headers
      • Request
      • Response
      • Streams
        • ReadableStream
        • ReadableStreamBYOBReader
        • ReadableStreamDefaultReader
        • TransformStream
        • WritableStream
        • WritableStreamDefaultWriter
      • Web Crypto
      • Web standards
      • Images
        • ImageProperties
    • Sample Functions
      • Example Overview
      • Obtaining Client URL Information
      • Customization Based on Client Geo Location
      • Obtaining Client Geo Location Information
      • Batch Redirect
      • URL rewrite based on regular expressions
      • Returning an HTML Page
      • Returning a JSON Object
      • Fetch Remote Resources
      • Authenticating a Request Header
      • Modifying a Response Header
      • Performing an A/B Test
      • Setting Cookies
      • Performing Redirect Based on the Request Location
      • Using the Cache API
      • Caching POST Requests
      • Responding in Streaming Mode
      • Merging Resources and Responding in Streaming Mode
      • Protecting Data from Tampering
      • Rewriting a m3u8 File and Configuring Authentication
      • Adaptive Image Resize
      • Image Adaptive WebP
      • Customize Referer restriction rules
      • Remote Authentication
      • HMAC Digital Signature
      • Naming a Downloaded File
      • Obtaining Client IP Address
      • Complex origin-pull URL rewriting
      • Web Bot Auth
    • Practical Tutorial
      • Overview
      • Origin retrieval based on user IP/geographic location
        • EdgeOne Implementation of Session Persistence Based on Client IP Addresses
        • EdgeOne Implementation of Origin-Pull Based on Client's Geo Location
      • APK dynamic packaging
        • EdgeOne enables dynamic packaging of Android APKs.
          • Feature Overview
          • Step 1: Preprocess the Android APK Parent Package
          • Step 2: Write the Channel Information into the APK Package with EdgeOne Edge Functions
      • Canary Release and Region-specific Execution
      • Adaptive Image Format Conversion via Edge Functions
      • Two Ways to Implement CDN Origin-pull Via Edge Function: Fetch and Passthrough
  • KV Storage
    • Overview
    • Operation Guide
  • Edge reasoning
    • Edge Inference Overview
    • Quick Guide

Cache

Cache is designed based on the Web APIs standard Cache API. The edge functions runtime injects a caches object globally, which provides a set of cache operation interfaces.
Note:
Cached content is valid only on the current data node and is not automatically replicated to other data nodes.

Cache Space

The Cache API involves two mutually isolated cache spaces: EdgeOne site cache and edge functions independent cache, distinguished by whether the default namespace is used and whether the Request carries eo.cacheKey .
Cache Space
Triggering Conditions
Writer
Available Operations in Function
EdgeOne site cache
Uses the default namespace and the Request does not carry eo.cacheKey.
Written by EdgeOne based on site cache rules.
Only cache.match
Edge function independent cache
Uses a non-default namespace, or the Request carries eo.cacheKey.
Written by cache.put within the function
cache.match / cache.put / cache.delete
The two types of caches are isolated from each other: cache operations on the edge functions independent cache do not hit the EdgeOne site cache.
Write and delete operations are supported only for the edge functions independent cache: when the default namespace is used and eo.cacheKey is not carried, the operations are rejected and a forbidden cdn cache error is thrown.
When a string type parameter is used, the edge functions runtime constructs a GET Request with it as the URL, and this Request does not carry eo.cacheKey: in the default namespace, read, write, and delete operations all belong to the EdgeOne site cache space, meaning that only site cache reads are allowed, while writes and deletes are also rejected. To read or write cache within a function, use a Request object to specify eo.cacheKey, or use a non-default namespace.
Recommendation: To read or write cache in edge functions, use the edge functions independent cache consistently (either by specifying eo.cacheKey or by using a non-default namespace). Use the same Request object for read, write, and delete operations to form a closed read-write loop. Caching of site resources is still controlled by site cache rules.
eo.cacheKey is carried through the first parameter (request) of cache.match, cache.put, and cache.delete: construct it using a Request object, for example, new Request(url, { eo: { cacheKey: 'xxx' } }) (see RequestInitEoProperties for details).
The cache key of the edge functions independent cache is composed of the namespace, the Request URL, and eo.cacheKey: when all three are identical, they correspond to the same cache entry, and if any one differs, they are isolated from each other.

Sample Code

addEventListener('fetch', (event) => {
event.respondWith(handleRequest(event));
});

async function fetchOrigin(event, cache, cacheKey) {
const response = await fetch(event.request);
response.headers.set('Cache-Control', 's-maxage=60');
event.waitUntil(cache.put(cacheKey, response.clone()));
return response;
}

async function handleRequest(event) {
const cache = caches.default;

// Read, write, and delete use the same Request object with eo.cacheKey specified
const cacheKey = new Request(event.request.url, {
eo: { cacheKey: 'page-home-v1' },
});

try {
let response = await cache.match(cacheKey);
if (!response) {
response = await fetchOrigin(event, cache, cacheKey);
}
return response;
} catch (error) {
// Exceptions such as cache expiration (504): Delete the old cache, then perform origin-pull again and write the result
try {
await cache.delete(cacheKey);
} catch (e) {}
return fetchOrigin(event, cache, cacheKey);
}
}

Constructor

You can use caches.default to obtain the default cache instance.
// Get the default cache instance
const cache = caches.default;

// The effect is equivalent to caches.default
await caches.open('default');
Use caches.open to create a cache instance in the specified namespace.
// Create a cache instance in the specified namespace
const cache = await caches.open(namespace);

Parameters

The parameters of the caches.open(namespace) method are described as follows.
Parameter Name
Type
Required
Description
namespace
string
Yes
Cache namespace.
If the value is "default", it indicates the default instance. You can also directly use caches.default to obtain the default instance.
For an instance created with a non-default namespace, all cache operations are performed in the edge functions independent cache and do not hit the EdgeOne site cache. For details on the differences, see Cache Space.

Instance Methods

match

cache.match(request: Request | string, options?: MatchOptions): Promise<Response | undefined>
Obtain the cached Response object associated with the request. A Promise object is returned. If the cache exists, it contains the Response object, otherwise it contains undefined.
Attention
cache.match does not actively perform origin-pull internally. If the cache has expired, a 504 error is thrown.
To match the EdgeOne site cache (for example, to determine in a function whether a resource is cached), it is recommended to use a Request object created with the target resource URL for matching, for example, cache.match(new Request('https://example.com/a.html')). Directly passing the client request object (such as event.request) may fail to hit the cache because it carries additional request headers.

Parameters

Parameter Name
Type
Required
Description
request
Request | string
Yes
Cache request object.
The request only supports the GET method. When the type is string, it is used as a URL to construct a Request object.
Cache space read: When the default namespace is used and the request does not carry eo.cacheKey, the EdgeOne site cache is read. When a non-default namespace is used or the request carries eo.cacheKey, the edge functions independent cache is read. For details on the differences, see Cache Space. Recommendation: When reading the edge functions independent cache, use the same Request object as cache.put and cache.delete.
When the request contains the Range header and the cached Response supports Range processing, a 206 response is returned.
When the request contains the If-Modified-Since header, and the cached Response has the Last-Modified header, and the Last-Modified value is equal to If-Modified-Since, a 304 response is returned.
When the request contains the If-None-Match header, and the cached Response has the ETag header, and the ETag value is equal to If-None-Match, a 304 response is returned.
options
No
Configuration option.

MatchOptions

Property Name
Type
Example Value
Description
ignoreMethod
boolean
true
Whether to ignore the method of the Request. When set to true, the original method of the Request is ignored and processed as GET.

put

cache.put(request: Request | string, response: Response): Promise<void>
Attempts to write the response to the edge functions independent cache using the given request as the cache key. If the write succeeds, a Promise<undefined> object is returned. If the default namespace is used and eo.cacheKey is not carried, the write is rejected. For details, see the parameters below.
Note:
When the Cache-Control header of the response object indicates no caching, a 413 error is thrown.

Parameters

Parameter Name
Type
Required
Description
request
Request | string
Yes
Cache request object.
The request only supports the GET method. When the type is string, it is used as a URL to construct a Request object.
When the default namespace is used and eo.cacheKey is not carried, the write target is the EdgeOne site cache, and the write is rejected with a forbidden cdn cache error. Otherwise, the write target is the edge functions independent cache. For other differences, see Cache Space.
response
Yes
Cached content, described as follows.
Cache-Control
Supports s-maxage, max-age, no-store, no-cache, and private. Among them, no-store, no-cache, and private indicate no caching, and cache.put returns a 413 error.
Pragma
When Cache-Control is not set and Pragma is no-cache, caching is not performed.
ETag
When the request parameter of cache.match contains the If-None-Match header, it can be used in association with ETag.
Last-Modified
When the request parameter of cache.match contains the If-Modified-Since header, it can be used in association with Last-Modified.
416 Range Not Satisfiable
When the response object is 416 Range Not Satisfiable, caching is not performed.

Parameter Limits

cache.put throws a parameter error when the following parameter values are used:
The request parameter is a method other than GET.
The status code of the response parameter is 206 Partial Content.
The response parameter contains the Vary: * header.

delete

cache.delete(request: Request | string, options?: DeleteOptions): Promise<boolean>
Deletes the cached response associated with the request. If no network error occurs, a Promise is always returned and contains true, otherwise it contains false.

Parameters

Parameter Name
Type
Required
Description
request
Request | string
Yes
Cache request object.
The request only supports the GET method. When the type is string, it is used as a URL to construct a Request object.
When the default namespace is used and eo.cacheKey is not carried, the deletion target is the EdgeOne site cache, and the deletion is rejected with a forbidden cdn cache error. Otherwise, the deletion target is the edge functions independent cache. For other differences, see Cache Space.
options
No
Configuration option.

DeleteOptions

Property Name
Type
Example Value
Description
ignoreMethod
boolean
true
Whether to ignore the method name of request. When set to true, the original method of the Request is ignored and processed as GET.

References