Cache-Tag Middleware

Tag-based HTTP caching with automatic invalidation driven by endpoint annotations

Basic Usage

import { cacheTags } from '@cleverbrush/client/cache';

const client = createClient(api, {
    middlewares: [cacheTags({ defaultTtl: 5000 })],
});

// First call hits the network
await client.todos.list({ query: { page: 1 } });

// Within 5 seconds — cache hit, no network request
await client.todos.list({ query: { page: 1 } });

Server Integration

Cache tags are declared on the server-side endpoint definition via .clearsCacheTag(). Tags flow through the contract metadata to the client automatically.

// contract.ts
const ListTodos = todosResource
    .get()
    .query(TodoListQuerySchema)
    .cacheTag('todo-list', p => ({
        page: p.query.page,
        limit: p.query.limit
    }))
    .returns(array(TodoSchema));

const UpdateTodo = todosResource
    .patch(ById)
    .body(UpdateTodoBodySchema)
    .clearsCacheTag('todo-list')            // invalidates list
    .clearsCacheTag('todo', p => ({        // invalidates entity
        id: p.params.id
    }))
    .returns(TodoSchema);

External Cache Invalidation

Use externalCacheTags() to send endpoint .clearsCacheTag() metadata to any external cache system after successful mutations.

import { createClient } from '@cleverbrush/client';
import { externalCacheTags } from '@cleverbrush/client/cache';

const client = createClient(api, {
    middlewares: [
        externalCacheTags({
            invalidateTag: tag => externalCache.invalidate(tag),
        }),
    ],
});

// Next.js example:
import { revalidateTag } from 'next/cache';
externalCacheTags({ invalidateTag: revalidateTag });

How It Works

  • On GET: Computes cache key from the endpoint's cache tag names and property selectors. Serves cached response if within TTL.
  • On mutation (POST/PUT/PATCH/DELETE): After a successful response, invalidates entries whose tag names start with any of the endpoint's tag names. Failed writes preserve entries; older in-flight reads cannot refill an invalidated response or its aliases.
  • Property-based keys: Tags with properties differentiate cache entries by request params, query, body, or headers (e.g. different pages get different cache keys).
  • TanStack Query bridge: When used with @cleverbrush/client/react, useMutation hooks automatically invalidate TanStack Query cache for the affected group.

Deterministic cache keys

Server and client helpers, response caches and external invalidation share the deterministic ct2: format. Property and object key order is normalized, values retain their types, and dates retain milliseconds. Even a property-free tag computes to ct2:["records",[]]. Unsupported selected values throw TypeError.

External cache writers and invalidators must use the same key format. Base invalidation labels are literal names. External invalidators send both base labels and computed keys by default, including property-free tags.

Response shape and auth/tenant isolation remain consumer-owned: use distinct list/detail names and select every value that affects a response. URLs and identities are not automatically included in keys. External caches need their own protection against stale concurrent writers.

Options

API reference table
OptionTypeDefault
defaultTtlnumber0
ttlByTag{ [tagName: string]: number }{ }
condition(response) => booleanresponse.ok

Set defaultTtl: 0 for invalidation-only mode: GET responses are not cached, but mutations still invalidate entries created by other endpoints.