Skip to content

Data/HTML caching

Caching stores the result of a catalog query or a rendered HTML page so a request does not hit the database again. In principle it shortens time to first byte. A cache that lives in isolate memory does not persist across isolates on a host like Workers, so a portable setup needs persistent KV, Blobs, or Cache-API storage; this repo hand-writes host-specific caches for that reason.

04 / 14First-paint leverOne of 7 features that affect first paint, the moment the browser first draws content. Together they are worth 14 of the 28 points.

Labels across 23 frameworks

  • 1st-party17
  • Experimental0
  • Third-party1
  • Manual5
  • of 23

How to enable it, by framework

One card per framework, in the same order on every feature page. Where a framework has no built-in support (Manual), a short example shows how to build it yourself.

Next

1st-party2 ptsOverview

Turn on cacheComponents: true (enabled here), then mark queries with 'use cache' and cacheLife('hours').

const nextConfig: NextConfig = {
  cacheComponents: true,
};
export async function getBooksPage(query: BookQuery): Promise<BookSummary[]> {
  'use cache';
  cacheLife('hours');
  // ...query the database
}

From this repo's next-books/next.config.ts (other options omitted) and features/book/book-queries.ts (query body omitted).

Nuxt

1st-party2 ptsOverview

Wrap handlers in defineCachedEventHandler (the Nitro v2 API that this Nuxt 4 port runs on, nitropack 2.13.4; Nitro v3 calls it defineCachedHandler), configure nitro.storage.cache, and add a header-only routeRules cache. The optimized branch uses the Vercel runtime cache, and the max branch adds Netlify Blobs and Cloudflare KV drivers.

export default defineCachedEventHandler(
  async event => { /* ... */ },
  {
    getKey: event => hashCacheKey(/* filters from the query */),
    maxAge: 60 * 60,
    name: 'books-count',
    swr: true,
  },
);
routeRules: {
  '/**': { cache: { headersOnly: true, maxAge: 3600 } },
  '/api/**': { cache: false },
},

From this repo's nuxt-books/server/api/books/count.get.ts (optimized branch; handler body elided) and nuxt.config.ts (nuxt-books-optimized-max branch).

SvelteKit

1st-party2 ptsOverview

Use adapter-vercel's per-route isr option, exported as config from a route, as done in src/lib/server/page-isr.ts. SvelteKit also has first-party, host-independent pieces: setHeaders in load for cache-control (this port sets it in src/routes/+layout.server.ts) and per-route prerender. The experimental remote functions only dedupe a query within one request (and share it on the client while it is in use); their prerender variant stores build-time data. This port turns on the remoteFunctions flag but defines no remote functions. A cross-request data cache on other hosts is manual: src/lib/server/catalog-cache.ts with Vercel Cache, Netlify Blobs, and the Workers KV/Cache API paths.

export const catalogIsrConfig = {
  isr: { expiration: CATALOG_CACHE_REVALIDATE_SECONDS, allowQuery: ['page', 'search'] }
} satisfies Config;
// src/routes/+page.server.ts
export const config = catalogIsrConfig;

From this repo's svelte-books/src/lib/server/page-isr.ts and src/routes/+page.server.ts (optimized branch; allowQuery shortened and spread removed).

SolidStart

Third-party1 ptOverview

Nitro, the server layer under Solid's start mode, caches routes and handlers: routeRules with cache or swr, plus defineCachedHandler. Nitro is maintained by the Nitro project (nitrojs), not the Solid team, so this counts as third-party, the same basis as SolidStart's multi-host cell. Solid Router's first-party query cache dedupes and caches client-side data only. Route pre-rendering covers any route listed in routes or crawled via nitro.prerender. The optimized port configures no cache, so its loaders in src/features/book/book-queries.ts query Postgres on a cold request. Our feature test sets routeRules: { "/feature-tests/caching": { cache: { maxAge: 2 } } } on Nitro 3 beta: the second request inside the TTL returns the same timestamp with x-cache: HIT, and a request after the TTL gets a new one.

routeRules: {
  "/blog/**": { swr: 3600 },
},

Adapted from the Nitro cache docs; the optimized port does not set it.

Use static prerendering plus per-route Cache-Control / stale-while-revalidate headers, which the ISR guide describes; the CDN does the revalidating, so there is no framework data cache.

export const Route = createFileRoute('/posts/$id')({
  headers: () => ({
    'Cache-Control': 'public, s-maxage=3600, stale-while-revalidate=86400',
  }),
})

From the ISR guide (its Vercel example; the guide's generic example also sets max-age=3600). This port uses src/lib/catalog-cache.ts plus a request middleware that sets document Cache-Control headers in src/start.ts:

const result = await next()
const headers = new Headers(result.response.headers)
headers.set('Cache-Control', hostDocumentCacheControl())

From this repo's tanstack-books/src/start.ts (optimized branch; abridged).

Static prerendering and route headers work the same way as in React (same snippet), but there is no Solid ISR guide. This port uses its own catalog cache plus Cache-Control headers.

Our feature test of the router loader cache (staleTime) passes on 2.0.0-rc.8: the loader made no server-function request inside staleTime, refetched once after it expired, and the new value reached the page. The label rests on prerendering and route headers; the loader cache is a bonus.

Code example

Give a route a headers function to set Cache-Control on its document response. Add prerender to tanstackStart() for pages that should be built ahead of time.

// src/routes/$id.tsx
import { createFileRoute } from '@tanstack/solid-router'

export const Route = createFileRoute('/$id')({
  loader: ({ params }) => getBook(params.id),
  headers: () => ({
    // Cache at CDN for 1 hour, allow stale content for up to 1 day
    'Cache-Control':
      'public, max-age=3600, s-maxage=3600, stale-while-revalidate=86400',
  }),
  // …
})

Source: TanStack Start: Incremental Static Regeneration (ISR)

Pracht

1st-party2 ptsOverview

ISG (render: "isg" with revalidate: timeRevalidate(3600), or webhookRevalidate()) is a per-route rendering mode. This port uses isg on both routes and adds src/lib/catalog-cache.ts for host-aware data caching.

route('/', './routes/home.tsx', {
  id: 'home',
  render: 'isg',
  revalidate: timeRevalidate(3600),
}),

From this repo's pracht-books/src/routes.ts (optimized branch; shell omitted).

Waku

1st-party2 ptsOverview

waku-cache is a separate, still-evolving package from the wakujs org; Waku has no core cache by design, and the migration guide says to add caching explicitly. The current waku-cache (0.0.2) requires Waku 1.0.0-rc.4 or later; this port runs rc.5 with waku-cache 0.0.2.

// ./src/lib/cache.ts
import { createCache } from 'waku-cache';
import { memoryStore } from 'waku-cache/stores/memory';
export const cache = createCache({
  store: memoryStore(),
  defaults: { ttl: 60_000 },
});

Adapted from the explicit-caching guide; the guide notes the memory store is process-local. On optimized this port uses it in src/lib/catalog-cache.ts: a memory store in front of each host's shared store (Workers KV, Vercel Runtime Cache or Netlify Blobs) through unstorageStore. src/middleware/html-cache-control.ts sets the HTML Cache-Control (main has neither).

Ember

Manual0 ptsOverview

On optimized, server/catalog-cache.js plus public/_headers (the header for the static SPA shell that the Netlify and Cloudflare deploys serve); main has neither. Where this port server-renders (the Node server and the Vercel function; the Netlify and Cloudflare deploys serve the un-rendered index.html shell plus API functions), SSR comes from vite-ember-ssr, a community, experimental package (not official; FastBoot is the official SSR path), which provides no data cache. WarpDrive/EmberData ships a first-party client request cache with expiry policies (CachePolicy / DefaultCachePolicy; repo), but no server, HTML, or edge caching; this port does not use it.

/
  Cache-Control: private, no-cache, no-store, max-age=0, must-revalidate

From this repo's ember-books/public/_headers (optimized branch; the /index.html rule omitted).

Astro

1st-party2 ptsOverview

Route caching for on-demand pages (astro@7.0.0+): top-level cache: { provider } with memoryCache(), Astro.cache.set({ maxAge, swr, tags }), routeRules, cache.invalidate(). Host providers (cacheNetlify(), cacheVercel(), cacheCloudflare()) are experimental and manually enabled. Also Vercel isr: true and Netlify cacheOnDemandPages. (caching, astro-7, vercel, netlify)

Code example

Pick a cache provider in the config, then set cache options from an on-demand page. routeRules sets defaults for groups of routes, and cache.invalidate() purges by tag or path.

// astro.config.mjs
import { defineConfig, memoryCache } from 'astro/config';

export default defineConfig({
  cache: { provider: memoryCache() },
  routeRules: {
    '/books/[...slug]': { maxAge: 3600, tags: ['books'] },
  },
});
---
// src/pages/index.astro
export const prerender = false;
Astro.cache.set({ maxAge: 120, swr: 60, tags: ['home'] });
---
// src/pages/api/revalidate.ts
import type { APIRoute } from 'astro';

export const POST: APIRoute = async (context) => {
  await context.cache.invalidate({ tags: ['books'] });
  return new Response(null, { status: 204 });
};

Source: Astro: Route caching

React Router

1st-party2 ptsOverview

Route headers export sets Cache-Control (deepest route wins; parentHeaders merges). prerender config is build-time only, with no ISR/revalidate option. Vercel's docs show s-maxage=1, stale-while-revalidate=59 via headers. (headers, pre-rendering, react-router)

Code example

Export headers from a route module to set Cache-Control on that route's document response. A child route can read parentHeaders and overwrite one value.

// app/routes/book.tsx
import type { Route } from './+types/book'

export function headers({ parentHeaders }: Route.HeadersArgs) {
  parentHeaders.set(
    'Cache-Control',
    'max-age=3600, s-maxage=86400',
  )
  return parentHeaders
}

Source: React Router: HTTP Headers

Qwik City

1st-party2 ptsOverview

cacheControl({ staleWhileRevalidate, maxAge, sMaxAge, public }) in onGet per layout/route. SSG via the static adapter; no data cache and no ISR documented. (caching, static-site-generation)

Code example

Call cacheControl in a layout's or route's onGet to set the Cache-Control header for every page under it. A nested layout can override it.

// src/routes/layout.tsx
import type { RequestHandler } from '@builder.io/qwik-city'

export const onGet: RequestHandler = async ({ cacheControl }) => {
  cacheControl({
    public: true,
    maxAge: 5,
    sMaxAge: 10,
    staleWhileRevalidate: 60 * 60 * 24 * 365,
  })
}

Source: Qwik: Caching responses

Angular (SSR)

1st-party2 ptsOverview

RenderMode.Prerender build-time HTML; the HttpClient transfer cache (withHttpTransferCacheOptions) reuses SSR responses on hydration; per-route headers. No ISR/revalidate or server data cache documented. (ssr, withHttpTransferCacheOptions)

Code example

Prerender stable pages at build time, and let the HttpClient transfer cache hand SSR responses to the browser so hydration does not fetch them again.

// src/app/app.routes.server.ts
export const serverRoutes: ServerRoute[] = [
  { path: 'about', renderMode: RenderMode.Prerender },
  { path: '**', renderMode: RenderMode.Server, headers: { 'Cache-Control': 'public, max-age=60' } },
];

// src/app/app.config.ts
import { provideClientHydration, withHttpTransferCacheOptions } from '@angular/platform-browser';

providers: [
  provideClientHydration(
    withHttpTransferCacheOptions({
      includeHeaders: ['ETag', 'Cache-Control'],
      filter: (req) => !req.url.includes('/api/profile'),
      includePostRequests: false,
    }),
  ),
],

Source: Angular: Server and hybrid rendering

Marko

Manual0 ptsOverview

Marko Run documents no data cache, ISR, or cache-header API. @marko/run-adapter-static builds the whole app into static files by crawling relative links (urls option for extras), with no revalidation and no per-route choice, so it does not cache a server-rendered app. Otherwise the app hand-sets Cache-Control on web-standard Request/Response, the same basis as Fresh. Our feature test passed only by setting Cache-Control by hand in the route's GET handler. (adapters)

Code example

For a fully static site, swap in @marko/run-adapter-static, which crawls links at build time; urls adds pages the crawler can't reach. For server-rendered pages, set Cache-Control yourself in middleware, as the Books port does.

// vite.config.ts (static build)
import { defineConfig } from "vite";
import marko from "@marko/run/vite";
import staticAdapter from "@marko/run-adapter-static";

export default defineConfig({
  plugins: [marko({ adapter: staticAdapter({ urls: ["/about", "/1"] }) })],
});
// src/routes/+middleware.ts (server build)
export default async (_ctx: unknown, next: () => Promise<Response>) => {
  const response = await next();
  if (!response.headers.get("content-type")?.includes("text/html")) return response;
  const headers = new Headers(response.headers);
  headers.set("Cache-Control", "public, max-age=0, must-revalidate");
  return new Response(response.body, { status: response.status, headers });
};

Source: Marko Run: Adapters

Fresh

Manual0 ptsOverview

No first-party cache documented; set Cache-Control by hand via page(data, { headers }). Build-time prerender exists only as an open, unmerged PR, not in the docs and not credited. (data-fetching, 3766)

Code example

You wrap each query in a TTL cache backed by a host store, and set the HTML Cache-Control in app middleware. This comes from the port.

// lib/catalog-cache.server.ts
export function withTtlCache<Args extends unknown[], Result>(
  name: string,
  fn: (...args: Args) => Promise<Result>,
): (...args: Args) => Promise<Result> {
  // in-memory Map → Workers KV / Vercel getCache / Netlify Blobs → fn()
  return (...args: Args) => cacheLifeHours(`${name}:${JSON.stringify(args)}`, () => fn(...args))
}

// features/book/book-queries.server.ts
export const getBooksPage = withTtlCache('getBooksPage', getBooksPageUncached)

// main.ts
app.use(async (ctx) => {
  const res = await ctx.next();
  if (!res.headers.get("content-type")?.includes("text/html")) return res;
  const headers = new Headers(res.headers);
  headers.set("Cache-Control", hostDocumentCacheControl());
  return new Response(res.body, { status: res.status, statusText: res.statusText, headers });
});

Source: Fresh data fetching

Analog

1st-party2 ptsOverview

analog({ prerender: { routes } }) renders listed routes to static HTML at build time, static: true builds a server-less site, and prerendered server-side data is written as static files. Response headers are set with h3 setResponseHeader in middleware or API routes. No ISR or revalidate option documented. (static-site-generation, middleware)

Code example

List routes under prerender.routes to build them as static HTML. Set staticData: true on a route to write its server-side data to static files too. Dynamic responses get headers from server middleware.

// vite.config.ts
import analog from '@analogjs/platform';
import { defineConfig } from 'vite';

export default defineConfig(() => ({
  plugins: [
    analog({
      prerender: {
        routes: async () => ['/', '/about', { route: '/books', staticData: true }],
      },
    }),
  ],
}));
// src/server/middleware/cache.ts
import { defineEventHandler, setResponseHeader } from 'h3';

export default defineEventHandler((event) => {
  if (event.path.startsWith('/books/')) {
    setResponseHeader(event, 'Cache-Control', 'public, s-maxage=60, stale-while-revalidate=300');
  }
});

Source: Analog: Static site generation, Analog: Middleware

Vike

1st-party2 ptsOverview

prerender: true renders pages to static HTML at build time, per page or for the whole app. +headersResponse sets response headers such as Cache-Control per page; it is marked beta. On Vercel, vercel: { isr: { expiration: 30 } } in a page's +config.js opts into ISR through vite-plugin-vercel. No data cache documented. (pre-rendering, headersResponse, vercel)

Code example

prerender: true builds pages to HTML. A dynamic page sets Cache-Control with +headersResponse. On Vercel, a page's +config can opt into ISR.

// pages/+config.ts
export default { prerender: true }

// pages/search/+config.ts
export default { prerender: false }

// pages/search/+headersResponse.ts
export function headersResponse() {
  return { 'Cache-Control': 'public, s-maxage=60, stale-while-revalidate=600' }
}

// pages/book/@id/+config.ts (Vercel only, with vite-plugin-vercel)
export default { vercel: { isr: { expiration: 30 } } }

Source: Vike: Pre-rendering · Vike: headersResponse · Vike: Vercel

No prerender, ISR or cache API documented; set Cache-Control by hand on the response headers. The client-navigation guide says RSC payload requests are GETs so browsers and CDNs can cache them. (routing, client-side-nav)

Code example

Put a small handler in front of the page in the route's array and set Cache-Control on response.headers. The browser and Cloudflare's edge then cache the HTML for that route.

// src/worker.tsx
import { defineApp } from "rwsdk/worker";
import { render, route } from "rwsdk/router";
import { Document } from "@/app/Document";
import { BookPage } from "@/app/pages/BookPage";

export default defineApp([
  render(Document, [
    route("/books/:id", [
      ({ response }) => {
        response.headers.set("Cache-Control", "public, max-age=60, s-maxage=300");
      },
      BookPage,
    ]),
  ]),
]);

Source: RedwoodSDK: Request Handling, Routing & Responses

Remix 3

Manual0 ptsOverview

No prerender, ISR or data cache documented; actions return standard Response objects and set Cache-Control by hand. Fingerprinted assets are served with Cache-Control: public, max-age=31536000, immutable. (request-handling, assets)

Code example

There is no data or HTML cache, so each action sets Cache-Control on its own response. context.render() takes a ResponseInit for that.

// app/actions/books/controller.tsx
import { createController } from "remix/router";
import { routes } from "../../routes.ts";
import { getBook } from "./data.ts";
import { BookPage } from "./show-page.tsx";

export default createController(routes.books, {
  actions: {
    async show(context) {
      let book = await getBook(context.params.bookId);
      if (!book) return new Response("Book not found", { status: 404 });

      return context.render(<BookPage book={book} />, {
        headers: { "Cache-Control": "public, max-age=60, s-maxage=300, stale-while-revalidate=600" },
      });
    },
  },
});

Source: Remix: Rendering UI, rendering pages through request context

Void (React)

1st-party2 ptsOverview

ISR with routing.revalidate (global or per path), a per-page export const revalidate = 120, an x-revalidate response header, and on-demand purge with revalidate({ paths }) from void/isr. Pages can be prerendered at deploy time (export const prerender = true) or at build time (output: "static"). ISR and edge prerendering need the Cloudflare target, where Void provisions the cache itself; routing.revalidate is ignored on Node, Bun and Deno. The client keeps prefetched page data for cacheFor (default '30s'). (revalidation, prerendering, ssg, cloudflare, nodejs-bun-deno)

Code example

On Cloudflare, give a page a revalidate time and Void caches the rendered HTML (ISR); revalidate({ paths }) from void/isr purges it. On Node, Bun and Deno ISR is ignored, so set Cache-Control with routing.headers.

// pages/index.server.ts
import { defineHandler } from 'void'

export const revalidate = 120 // seconds, Cloudflare target

export const loader = defineHandler(async () => ({ books: await listBooks() }))
// void.config.ts
import { defineConfig } from 'void/config'

export default defineConfig({
  routing: { headers: { '/': ['Cache-Control: public, s-maxage=120, stale-while-revalidate=600'] } },
})

Source: Void: Revalidation · Void: Headers

Void (Vue)

1st-party2 ptsOverview

ISR with routing.revalidate (global or per path), a per-page export const revalidate = 120, an x-revalidate response header, and on-demand purge with revalidate({ paths }) from void/isr. Pages can be prerendered at deploy time (export const prerender = true) or at build time (output: "static"). ISR and edge prerendering need the Cloudflare target, where Void provisions the cache itself; routing.revalidate is ignored on Node, Bun and Deno. The client keeps prefetched page data for cacheFor (default '30s'). (revalidation, prerendering, ssg, cloudflare, nodejs-bun-deno)

Code example

On Cloudflare, give a page a revalidate time and Void caches the rendered HTML (ISR); revalidate({ paths }) from void/isr purges it. On Node, Bun and Deno ISR is ignored, so set Cache-Control with routing.headers.

// pages/index.server.ts
import { defineHandler } from 'void'

export const revalidate = 120 // seconds, Cloudflare target

export const loader = defineHandler(async () => ({ books: await listBooks() }))
// void.config.ts
import { defineConfig } from 'void/config'

export default defineConfig({
  routing: { headers: { '/': ['Cache-Control: public, s-maxage=120, stale-while-revalidate=600'] } },
})

Source: Void: Revalidation · Void: Headers

Void (Svelte)

1st-party2 ptsOverview

ISR with routing.revalidate (global or per path), a per-page export const revalidate = 120, an x-revalidate response header, and on-demand purge with revalidate({ paths }) from void/isr. Pages can be prerendered at deploy time (export const prerender = true) or at build time (output: "static"). ISR and edge prerendering need the Cloudflare target, where Void provisions the cache itself; routing.revalidate is ignored on Node, Bun and Deno. The client keeps prefetched page data for cacheFor (default '30s'). (revalidation, prerendering, ssg, cloudflare, nodejs-bun-deno)

Code example

On Cloudflare, give a page a revalidate time and Void caches the rendered HTML (ISR); revalidate({ paths }) from void/isr purges it. On Node, Bun and Deno ISR is ignored, so set Cache-Control with routing.headers.

// pages/index.server.ts
import { defineHandler } from 'void'

export const revalidate = 120 // seconds, Cloudflare target

export const loader = defineHandler(async () => ({ books: await listBooks() }))
// void.config.ts
import { defineConfig } from 'void/config'

export default defineConfig({
  routing: { headers: { '/': ['Cache-Control: public, s-maxage=120, stale-while-revalidate=600'] } },
})

Source: Void: Revalidation · Void: Headers

Void (Solid)

1st-party2 ptsOverview

ISR with routing.revalidate (global or per path), a per-page export const revalidate = 120, an x-revalidate response header, and on-demand purge with revalidate({ paths }) from void/isr. Pages can be prerendered at deploy time (export const prerender = true) or at build time (output: "static"). ISR and edge prerendering need the Cloudflare target, where Void provisions the cache itself; routing.revalidate is ignored on Node, Bun and Deno. The client keeps prefetched page data for cacheFor (default '30s'). (revalidation, prerendering, ssg, cloudflare, nodejs-bun-deno)

Code example

On Cloudflare, give a page a revalidate time and Void caches the rendered HTML (ISR); revalidate({ paths }) from void/isr purges it. On Node, Bun and Deno ISR is ignored, so set Cache-Control with routing.headers.

// pages/index.server.ts
import { defineHandler } from 'void'

export const revalidate = 120 // seconds, Cloudflare target

export const loader = defineHandler(async () => ({ books: await listBooks() }))
// void.config.ts
import { defineConfig } from 'void/config'

export default defineConfig({
  routing: { headers: { '/': ['Cache-Control: public, s-maxage=120, stale-while-revalidate=600'] } },
})

Source: Void: Revalidation · Void: Headers

Gotchas

  • Host cache layers differ (Vercel runtime cache, Netlify Blobs, Cloudflare KV), so a "cache" written for one host needs a storage driver for the others.