Skip to content
Get started

Cache

ctx.cache is the regional edge cache available in every handler. The high-level method is swr(); get/set/delete exist for cases where you need explicit control. Concepts and patterns are covered in the edge caching guide.

cache.swr<T>(key: string, fetcher: () => Promise<T>, options?: SwrOptions): Promise<T>

Returns the cached value when fresh, returns stale-and-revalidates within the stale window, and runs the fetcher inline on a miss. Concurrent requests for the same key share a single fetcher call.

OptionTypeDefaultDescription
ttlnumber60Seconds the value is considered fresh
stalenumber600Seconds after ttl during which stale values serve while revalidating
tagsstring[][]Labels for tag-based purges

Defaults can be changed per app via vega.app({ cache }).

const product = await cache.swr(`product:${id}`, () => db.products.find(id), {
ttl: 120,
tags: ['products'],
});

Values must be structured-cloneable (JSON-compatible data, plus Date, Map, Set, and typed arrays).

cache.get<T>(key: string): Promise<T | undefined>

Reads a value without triggering any fetch. Stale values are returned (with revalidation left to you); expired values return undefined.

cache.set<T>(key: string, value: T, options?: { ttl?: number; tags?: string[] }): Promise<void>

Writes a value directly. Useful for warming the cache from a webhook or background job:

api.post('/webhooks/cms', async ({ request, cache }) => {
const page = await request.json();
await cache.set(`page:${page.slug}`, page, { ttl: 3600, tags: ['pages'] });
return Response.json({ ok: true });
});
cache.delete(key: string): Promise<void>

Removes a single key in the current region. For removal across all regions, use purge.

cache.purge(options: { keys?: string[]; tags?: string[] }): Promise<void>

Invalidates entries in all 28 regions, propagating in under 300ms:

await cache.purge({ tags: ['products'] });
await cache.purge({ keys: [`product:${id}`] });

The same operation is available from the CLI: vega cache purge --tag products.

Responses produced by handlers that touched the cache carry vega-cache:

ValueMeaning
hitFresh value served from cache
staleStale value served; revalidating in background
missFetcher ran inline
bypassNo cache call on this request
LimitValue
Key length512 bytes
Value size25 MB
Maximum ttl86,400 seconds (24 hours)
Maximum stale86,400 seconds (24 hours)
Tags per entry64