Documentation menuMenu da documentação

$ cat docs/middleware/edge-cache.md

Edge cacheCache na borda

Answer repeated public reads from the edge without running the handler, and never cache a personal or authenticated response.Responda leituras públicas repetidas pela borda sem rodar o handler, e nunca guarde uma resposta pessoal ou autenticada.

What it doesO que faz

edgeCache(options: EdgeCacheOptions): MiddlewareHandler. A hit answers before the handler runs; a miss runs it and stores a copy with waitUntil, so the response is not delayed. The route decides, not a list of paths: only GETs of routes whose access is 'public' with no authentication (an optional one could answer per user), whose response schema has no pii, health or secret field, from requests without authorization or cookie. Only 200s without set-cookie, private, no-store, no-cache or vary: * are stored. The stored copy gets s-maxage; a hit answers with the cache-control the app sent.

edgeCache(options: EdgeCacheOptions): MiddlewareHandler. Um acerto responde antes de o handler rodar; uma falta roda o handler e guarda uma cópia com waitUntil, sem atrasar a resposta. Quem decide é a rota, não uma lista de caminhos: só GET de rotas com access 'public' sem autenticação (uma opcional poderia responder por usuário), cujo schema de resposta não tem campo pii, health ou secret, de requisições sem authorization nem cookie. Só respostas 200 sem set-cookie, private, no-store, no-cache ou vary: * são guardadas. A cópia guardada recebe s-maxage; um acerto responde com o cache-control que o app enviou.

Install and orderInstalar e ordenar

terminal
pnpm add @tupik/middleware

Register it after the rate limiter (hits still count) and before the routes it should cover, on the app or on a module.

Registre depois do limitador de requisições (os acertos continuam contando) e antes das rotas que ele deve cobrir, no app ou num módulo.

ExampleExemplo

edge-cache.ts
import { createModule } from '@tupik/core';
import { edgeCache } from '@tupik/middleware';

const catalog = createModule('/catalog')
  .use(edgeCache({ maxAge: 300 })) // 5 minutes at the edge
  .get('/products/:id', { access: 'public', schema: { response: { 200: Product } }, handler: (ctx) => getProduct(ctx.params.id) });
import { createModule } from '@tupik/core';
import { edgeCache } from '@tupik/middleware';

const catalog = createModule('/catalog')
  .use(edgeCache({ maxAge: 300 })) // 5 minutos na borda
  .get('/products/:id', { access: 'public', schema: { response: { 200: Product } }, handler: (ctx) => getProduct(ctx.params.id) });

APIAPI

OptionOpçãoTypeTipoDefault / behaviorPadrão / comportamento
maxAge number Required. Seconds a stored response stays fresh (s-maxage).Obrigatório. Segundos em que a resposta guardada vale (s-maxage).
cache EdgeCacheStore caches.default when the runtime has it; elsewhere nothing is cached.caches.default quando o runtime tem; fora dele nada é guardado.
key (ctx) => string The request URL, path and query.A URL da requisição, caminho e query.
header boolean false. true adds x-tupik-cache: HIT, MISS or BYPASS.false. true adiciona x-tupik-cache: HIT, MISS ou BYPASS.

interface EdgeCacheOptions { maxAge: number; cache?; key?; header? }

interface EdgeCacheOptions { maxAge: number; cache?; key?; header? }

Errors and limitsErros e limites

  • A maxAge that is not a positive whole number throws at creation.
  • The Workers Cache API works only on a custom domain or route: on *.workers.dev it stores nothing.
  • Each Cloudflare data center keeps its own copy; there is no global purge from here.
  • Um maxAge que não seja número inteiro positivo lança na criação.
  • A Cache API do Workers só funciona com domínio próprio ou rota: em *.workers.dev ela não guarda nada.
  • Cada data center da Cloudflare guarda sua cópia; não há purga global por aqui.

When not to use itQuando não usar

For data that must be fresh on every read (stock, balances), keep the route uncached; for per-user responses the middleware already bypasses, so there is nothing to configure.

Para dado que precisa estar fresco em toda leitura (estoque, saldo), deixe a rota sem cache; respostas por usuário o middleware já ignora, sem nada a configurar.