Skip to main content
🔥
Reference

API Reference | @express-route-cache

Detailed documentation for createCache, middleware, route options, the standalone fetch API, CacheClient interface, and exported utilities.

API Reference

createCache(config)

The main entry point for initializing the caching layer.

CacheConfig Options

OptionTypeDefaultDescription
adapterCacheClient—Required. Storage adapter (Memory, Redis, Memcached).
staleTimenumber60Seconds data stays fresh. During this window, cached responses are returned instantly.
gcTimenumber300Seconds stale data is kept in cache before eviction. Total TTL = staleTime + gcTime.
swrbooleanfalseEnable Stale-While-Revalidate background refresh.
stampedebooleantruePrevent thundering-herd via request coalescing.
varystring[][]Request headers to include in the cache key (e.g. ['authorization']).
sortQuerybooleanfalseSort query params alphabetically for higher hit rates (?a=1&b=2 ≡ ?b=2&a=1).
maxBodySizenumber2097152Max response size in bytes to cache (default: 2MB). Larger responses skip the cache.
autoInvalidatebooleanfalseAuto-invalidate route pattern epochs on successful POST, PUT, PATCH, or DELETE.
retrynumber0Retries with exponential backoff for cache.fetch() on failure.
keyPrefixstring"erc:"Global prefix for all cache keys in Redis/Memcached.
enabledboolean | ((req: Request, res: Response) => boolean)trueToggle caching globally. Accepts boolean or callback function.
metricsbooleanfalseEnable real-time telemetry metrics collection (required for Cache Studio charts).
studioboolean | StudioOptionsfalseEnable the Cache Studio visual dashboard or configure a standalone server.

Returns (CacheInstance)

PropertyTypeDescription
middleware()() => ExpressMiddlewareGlobal middleware — caches all GET requests. Use with app.use().
route(opts?)(opts?: RouteOptions) => ExpressMiddlewarePer-route middleware with optional overrides.
invalidate(...patterns)(...patterns: string[]) => ExpressMiddlewareMiddleware: increments epochs on successful (2xx) response.
invalidateRoute(...patterns)(...patterns: string[]) => Promise<void>Programmatic invalidation from outside a request context.
fetch(key, fetcher, opts?)<T>(key, fetcher, opts?) => Promise<T>Standalone data caching with SWR, Stampede, and Retry support.
adapterCacheClientThe underlying storage adapter instance.
metricsCacheMetrics | undefinedLive telemetry counters (only defined when metrics: true).
studioboolean | StudioOptions | undefinedStudio configuration reference passed through from config.

cache.route(overrides?)

Apply specific caching rules to an individual route. All RouteOptions override global CacheConfig values for that route only.

RouteOptions

OptionTypeDescription
staleTimenumberOverride global staleTime for this route.
gcTimenumberOverride global gcTime for this route.
swrbooleanOverride global swr for this route.
enabledboolean | ((req: Request, res: Response) => boolean)Disable or enable caching for this route. Accepts boolean or callback function. Explicitly setting this to true or a callback allows caching POST / non-GET requests.
varystring[]Override global vary for this route.
sortQuerybooleanOverride global sortQuery for this route.
maxBodySizenumberOverride global maxBodySize for this route.
autoInvalidatebooleanOverride global autoInvalidate for this route. No-op when key override is also set — use cache.invalidate() instead.
retrynumberOverride global retry for this route.
keystring | (req: Request) => stringCustom key override. If provided, used instead of the auto-generated versioned key.
app.get(
  "/heavy-report",
  cache.route({
    staleTime: 3600, // 1 hour
    swr: true,
    key: (req) => `report:${req.user.id}`,
  }),
  handler,
);

cache.fetch(key, fetcher, opts?)

Standalone method for manual data caching — not tied to Express routes. Includes full SWR, Stampede Protection, and Retry logic.

For more advanced usage, see the Standalone Fetch Guide.

const data = await cache.fetch(
  "users-list",
  async () => {
    return await db.users.findMany();
  },
  {
    staleTime: 60,
    swr: true,
    retry: 3,
  },
);
OptionTypeDescription
staleTimenumberSeconds data stays fresh.
gcTimenumberSeconds stale data is kept.
swrbooleanEnable background revalidation on stale hit.
enabledbooleanDisable caching for this call.
maxBodySizenumberMax serialized payload size.
retrynumberRetry count with exponential backoff on fetcher failure.

cache.invalidate(...patterns)

Express middleware that increments the epoch version for specific patterns upon a successful (2xx) response.

app.post("/api/posts", cache.invalidate("/api/posts"), createPost);

cache.invalidateRoute(...patterns)

Programmatic invalidation — call from anywhere (service layer, cron job, webhook handler).

await cache.invalidateRoute("/api/users/123", "/api/users");

StudioOptions

Passed as studio: { ... } inside createCache().

OptionTypeDefaultDescription
enabledbooleantrueEnable or disable the Studio integration.
portnumber—If set, auto-starts a standalone Studio Express server on this port.
pathstring"/studio"Mount path for the dashboard.
hostnamestring"localhost"Hostname used in the console log URL message only (does not affect the bind address).

CacheMetrics

Exposed via cache.metrics when metrics: true is set in config.

const cache = createCache({ adapter, metrics: true });

// Poll metrics from a health endpoint
app.get("/health/cache", (req, res) => {
  res.json(cache.metrics);
});
FieldTypeDescription
hitsnumberFresh cache hits served instantly.
missesnumberCache misses that required handler execution.
swrHitsnumberStale responses served while a background revalidation was triggered.
swrFailuresnumberBackground revalidation attempts that threw an error.
stampedeCoalescesnumberRequests that coalesced onto an in-flight Promise instead of running the handler.
stampedePollsnumberFollower-server poll attempts resolved from the distributed cache (Redis/Memcached).

CacheClient Interface

The contract that every adapter must satisfy. Implement this interface to build a custom adapter.

import type { CacheClient } from '@express-route-cache/core';

const myAdapter: CacheClient = {
  name: "custom-adapter",
  async ping() { return true; },
  async get(key) { ... },
  async mget(keys) { ... },
  async set(key, value, ttlSeconds) { ... },
  async del(...keys) { ... },
  async incr(key) { ... },
  // Optional:
  async setNX(key, value, ttlSeconds) { ... },
  async keys(pattern) { ... },
  async disconnect() { ... },
};
Method / PropSignatureRequiredDescription
namestringOptionalHuman-readable adapter name used by Cache Studio for adapter type diagnostics.
ping() => Promise<boolean>OptionalConnection health check returning true on active connection; used by Cache Studio.
get(key: string) => Promise<string | null>✅Retrieve a value. Returns null on miss.
mget(keys: string[]) => Promise<(string | null)[]>✅Batch retrieve. Returns array in same order, null for misses.
set(key: string, value: string, ttl?: number) => Promise<void>✅Store a value with optional TTL in seconds.
del(...keys: string[]) => Promise<void>✅Delete one or more keys.
incr(key: string) => Promise<number>✅Atomically increment a counter (creates at 1 if missing). Used for epoch versioning.
setNX(key: string, value: string, ttl: number) => Promise<boolean>OptionalAtomically set only if key doesn't exist. Enables distributed Stampede + SWR locking.
keys(pattern?: string) => Promise<string[]>OptionalEnumerate all keys (optionally filtered). Required for Cache Studio key browser.
disconnect() => Promise<void>OptionalCleanup/disconnect hook. Called when the app shuts down.

[!IMPORTANT] Implementing setNX unlocks distributed Stampede Protection and SWR locking across multiple server instances. Without it, only in-process coalescing is active.


Advanced Utilities

These functions are exported from @express-route-cache/core for advanced use cases such as building custom adapters, debugging cache keys, or implementing custom invalidation strategies.

import {
  getRoutePattern,
  getParentRoutePatterns,
  buildVersionedKey,
  buildCacheKey,
  generateCacheKey,
  getFreshness,
  getAgeSeconds,
} from "@express-route-cache/core";
ExportDescription
getRoutePattern(req)Extracts the Express route pattern from a request (e.g. /users/:id).
getParentRoutePatterns(route)Returns all ancestor patterns for a route path (used for cascade invalidation).
buildVersionedKey(opts)Constructs a SHA-256 hashed cache key incorporating epochs, vary headers, and query params.
buildCacheKey(client, req, prefix, vary?, sortQuery?)Async wrapper that fetches epochs and calls buildVersionedKey.
generateCacheKey(tag, data, prefix?)Generates a type-safe SHA-256 hashed cache key based on a custom tag and uniqueness data.
getFreshness(entry, staleTime, gcTime)Returns "fresh" | "stale" | "expired" for a cache entry.
getAgeSeconds(entry)Returns the age of a cache entry in seconds.