Cloudflare
Caching

Caching

@opennextjs/cloudflare supports caching (opens in a new tab).

By default, all fetch() subrequests made in your Next.js app are cached. Refer to the Next.js documentation (opens in a new tab) for information about how to disable caching for an individual subrequest, or for an entire route.

The cache persists across deployments (opens in a new tab). You are responsible for revalidating/purging this cache.

Next.js primes the cache at build time. The build time values are serverd by the Workers Assets (opens in a new tab).

💡

Workers KV is eventually consistent, which means that it can take up to 60 seconds for updates to be reflected globally, when using the default TTL of 60 seconds.

How to enable caching

@opennextjs/cloudflare supports multiple caching mechanisms through a project's OpenNext configuration.

Incremental Static Regeneration (ISR)

The ISR adapter for Cloudflare uses Workers KV (opens in a new tab) as the cache for your Next.js app. Workers KV is fast (opens in a new tab) and uses Cloudflare's Tiered Cache (opens in a new tab) to increase cache hit rates. When you write cached data to Workers KV, you write to storage that can be read by any Cloudflare location. This means your app can fetch data, cache it in KV, and then subsequent requests anywhere around the world can read from this cache. Pricing information can be found in the Cloudflare docs (opens in a new tab).

1. Create a KV namespace
npx wrangler@latest kv namespace create <YOUR_NAMESPACE_NAME>
2. Add the KV namespace to your Worker

The binding name used in your app's worker is NEXT_CACHE_WORKERS_KV.

// wrangler.json
{
  // ...
  "kv_namespaces": [
    {
      "binding": "NEXT_CACHE_WORKERS_KV",
      "id": "<BINDING_ID>"
    }
  ]
}

3. Configure the cache

In your project's OpenNext config, enable the KV cache and set up a queue.

The memory queue will send revalidation requests to a page when needed, and offers support for de-duplicating requests on a per-isolate basis. There might still be duplicate requests under high traffic or across regions.

// open-next.config.ts
import incrementalCache from "@opennextjs/cloudflare/kv-cache";
import memoryQueue from "@opennextjs/cloudflare/memory-queue";
 
const config: OpenNextConfig = {
  default: {
    override: {
      // ...
      incrementalCache: () => incrementalCache,
      queue: () => memoryQueue,
    },
  },
  // ...
};
 
export default config;