Spoosh
Plugins

Cache

Response caching with configurable stale time

The cache plugin stores API responses and serves them instantly on subsequent requests, reducing network usage and improving perceived performance.

Installation

npm install @spoosh/plugin-cache

Usage

import { cachePlugin } from "@spoosh/plugin-cache";

const plugins = [
  cachePlugin({ staleTime: 5000 }), // 5 second stale time
];

Data is considered "fresh" for the duration of staleTime. During this period, subsequent requests return cached data without making a network request.

Per-Request Override

// Use longer cache time for static data
useRead((api) => api.settings.$get(), { staleTime: 60000 });

// Disable caching for real-time data
useRead((api) => api.live.$get(), { staleTime: 0 });

Options

Plugin Config

OptionTypeDefaultDescription
staleTimenumber0Default stale time in milliseconds

Per-Request Options

OptionTypeDescription
staleTimenumberOverride stale time for this request

How It Works

  1. First request fetches from network and stores in cache
  2. Subsequent requests within staleTime return cached data instantly
  3. After staleTime expires, next request fetches fresh data
  4. Cache is automatically invalidated when using invalidationPlugin

Combining with Invalidation

For automatic cache updates after mutations, combine with invalidationPlugin:

import { cachePlugin } from "@spoosh/plugin-cache";
import { invalidationPlugin } from "@spoosh/plugin-invalidation";

const plugins = [
  cachePlugin({ staleTime: 5000 }),
  invalidationPlugin(), // Auto-invalidates related caches after mutations
];

When a mutation succeeds, related cached queries are automatically refreshed.

On this page