Redis-based cache handler. Designed for Next.js but can be used to build custom caching solutions for any other stack
- Types
- ESM
- CJS
- License
- MIT
- Install Size
- 175.5 kB
- Vulns
- 0
- Published
npm install @nimpl/cache-redispnpm add @nimpl/cache-redisyarn add @nimpl/cache-redisbun add @nimpl/cache-redisdeno add npm:@nimpl/cache-redisvlt install @nimpl/cache-redisvp add @nimpl/cache-redis@nimpl/cache-redis
Redis-based cache handler with multi-pod support. Designed for Next.js but can be used to build custom caching solutions for any other stack (e.g. cache function in React Router 7 or Remix).
Overview
@nimpl/cache-redis is a showcase library that demonstrates how to build a cache handler using @nimpl/cache. It implements a two-tier caching strategy: an in-memory LRU cache for fast local access and Redis for shared cache across multiple pods.
Note: This is a showcase library. In most cases, you should build your own cache-handler using
@nimpl/cacheto have full control over configuration and layers.For detailed information on handlers, layers, custom implementations, and advanced configuration, see the
@nimpl/cacheREADME.
How It Works
The cache handler uses a layered approach:
- In-Memory Layer: LRU cache stores frequently accessed entries locally for sub-millisecond retrieval
- Redis Layer: Persistent cache shared across all pods, ensuring cache consistency in distributed deployments
- Pending Operations: Deduplicates concurrent read and write requests for the same key to prevent cache stampede
On cache miss in-memory, the handler fetches from Redis and populates the local LRU cache.
Installation
npm install @nimpl/cache-redis
# or
pnpm add @nimpl/cache-redis
Configuration
Next.js Setup
Configure the cache handler in next.config.ts:
import { type NextConfig } from "next/types";
const nextConfig: NextConfig = {
cacheComponents: true,
cacheHandlers: {
default: import.meta.resolve("@nimpl/cache-redis"),
},
};
export default nextConfig;
Options
The cache handler accepts the following parameters (all optional):
logger(Logger): Custom logging function. Default: console logger (enabled whenNEXT_PRIVATE_DEBUG_CACHEorNIC_LOGGERis set)lruOptions(LRUCache.Options): Options for theLRU cacheinstancemaxSize: Maximum cache size in bytes. Default:50 * 1024 * 1024(50MB) orLRU_CACHE_MAX_SIZEenv var (in MB)ttl(number | "auto"): Time-to-live in seconds. Default:"auto"
redisOptions(RedisOptions): Redis connection options fromioredisurl: Redis connection URL. Default:process.env.REDIS_URL || "redis://localhost:6379"connectionStrategy("ignore" | "wait-ignore" | "wait-throw" | "wait-exit"): Connection failure behavior. Default:"ignore"
Custom Configuration
You can initialize the cache handler with custom configuration:
// cache-handlers/redis.js
import { CacheHandler } from "@nimpl/cache-redis/cache-handler";
global.cacheHandler ||= new CacheHandler({
lruOptions: { maxSize: 100 * 1024 * 1024 },
redisOptions: { connectionStrategy: "wait-ignore" },
});
// next.config.ts
import { type NextConfig } from "next/types";
const nextConfig: NextConfig = {
cacheComponents: true,
cacheHandlers: {
default: import.meta.resolve("./cache-handlers/redis.js"),
},
};
export default nextConfig;
Note: It is recommended to write to
global, as otherwise the instance will be created differently for Next.js and for your independent use (for example, for cache-widget or your internal utilities). As a result, in-memory entries will be different, and will also be duplicated.
Usage
Next.js
Use Next.js cache APIs as usual:
import { cacheLife } from "next/cache";
export default async function Page() {
"use cache";
cacheLife({ stale: 30, revalidate: 60, expire: 120 });
// Your component logic
}
Other Frameworks
The cache handler can be used directly with @nimpl/cache-tools:
import { CacheHandler } from "@nimpl/cache-redis/cache-handler";
import { createCache } from "@nimpl/cache-tools";
const cacheHandler = new CacheHandler({
redisOptions: { keyPrefix: "admin:" },
});
export const { cache } = createCache(cacheHandler);
Additional Information
For detailed information on:
- Custom handlers and layers implementation
- Method specifications and requirements
- Health checks and readiness probes
- Multi-pod support details
- Serverless environment considerations
- Limitations and best practices
See the @nimpl/cache README.
Examples
- Base Example - Minimal Next.js example demonstrating filesystem cache handler and cache widget
- React Router Example - Source code
- Next.js cacheComponents Example - Source code