### Start Cache Lab Integration App
Source: https://github.com/trieb-work/nextjs-turbo-redis-cache/blob/main/README.md
Commands to install dependencies and start the local development server for manual cache testing.
```bash
pnpm -C test/integration/next-app-16-1-1-cache-components install
pnpm -C test/integration/next-app-16-1-1-cache-components dev
```
--------------------------------
### Install Redis Cache Handler
Source: https://github.com/trieb-work/nextjs-turbo-redis-cache/blob/main/README.md
Installation command for the required package and Redis client dependency.
```bash
pnpm add @trieb.work/nextjs-turbo-redis-cache redis
```
--------------------------------
### Start Next.js Development Server
Source: https://github.com/trieb-work/nextjs-turbo-redis-cache/blob/main/test/integration/next-app-16-0-3/README.md
Commands to initiate the local development server for the Next.js application. Supports multiple package managers including npm, yarn, pnpm, and bun.
```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```
--------------------------------
### Install Package (pnpm)
Source: https://github.com/trieb-work/nextjs-turbo-redis-cache/blob/main/README.md
Installs the @trieb.work/nextjs-turbo-redis-cache package using pnpm. This is the primary step to integrate the caching solution into your Next.js project.
```bash
pnpm install @trieb.work/nextjs-turbo-redis-cache
```
--------------------------------
### Start Next.js development server
Source: https://github.com/trieb-work/nextjs-turbo-redis-cache/blob/main/test/integration/next-app-16-1-1/README.md
Commands to initiate the local development server for the Next.js application. Supports multiple package managers including npm, yarn, pnpm, and bun.
```bash
npm run dev
yarn dev
pnpm dev
bun dev
```
--------------------------------
### Docker Deployment Configuration for Redis Cache
Source: https://context7.com/trieb-work/nextjs-turbo-redis-cache/llms.txt
Provides Dockerfile and docker-compose.yml configurations for deploying a Next.js application with Redis caching. These files set up the necessary environment variables, ports, and service dependencies for a production-ready setup, including Redis as a service.
```dockerfile
# Dockerfile
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
RUN npm run build
ENV NODE_ENV=production
ENV REDIS_URL=redis://redis:6379
ENV VERCEL_ENV=production
ENV KILL_CONTAINER_ON_ERROR_THRESHOLD=10
EXPOSE 3000
CMD ["npm", "start"]
```
```yaml
# docker-compose.yml
version: '3.8'
services:
app:
build: .
ports:
- "3000:3000"
environment:
- REDIS_URL=redis://redis:6379
- VERCEL_ENV=production
- KILL_CONTAINER_ON_ERROR_THRESHOLD=10
depends_on:
- redis
restart: unless-stopped
redis:
image: redis:7-alpine
command: redis-server --notify-keyspace-events Exe
ports:
- "6379:6379"
volumes:
- redis_data:/data
volumes:
redis_data:
```
--------------------------------
### Statically Cached Page with Fetch in Next.js
Source: https://context7.com/trieb-work/nextjs-turbo-redis-cache/llms.txt
Illustrates creating a statically cached page in Next.js using fetch operations that leverage Redis caching. This example shows how to define data fetching with revalidation and tags, suitable for pages with frequently accessed, but not real-time, data. The `dynamic = 'force-dynamic'` export ensures the page utilizes dynamic rendering with caching.
```typescript
async function getProducts() {
const response = await fetch('https://api.example.com/products', {
next: {
revalidate: 60, // Revalidate every 60 seconds
tags: ['products'],
},
});
return response.json();
}
export default async function ProductsPage() {
const products = await getProducts();
return (
Products
{products.map((product: { id: string; name: string }) => (
- {product.name}
))}
);
}
// Force dynamic rendering with caching
export const dynamic = 'force-dynamic';
```
--------------------------------
### Configure Next.js Cache Handler (JavaScript)
Source: https://github.com/trieb-work/nextjs-turbo-redis-cache/blob/main/README.md
Extends the next.config.js file to use the installed Redis cache handler. This configuration tells Next.js to use the package for its caching mechanisms. Ensure Redis environment variables are set.
```javascript
const nextConfig = {
...
cacheHandler: require.resolve("@trieb.work/nextjs-turbo-redis-cache")
...
}
```
--------------------------------
### Run Playwright E2E Tests
Source: https://github.com/trieb-work/nextjs-turbo-redis-cache/blob/main/README.md
Commands to execute end-to-end tests for the caching handler. Supports environment variables like SKIP_BUILD and DEBUG_INTEGRATION to control test behavior.
```bash
pnpm test:e2e
# Run against a specific dev server
PLAYWRIGHT_BASE_URL=http://localhost:3101 pnpm test:e2e
```
--------------------------------
### Configure TLS for Redis Connection in JavaScript
Source: https://github.com/trieb-work/nextjs-turbo-redis-cache/blob/main/README.md
Demonstrates how to configure TLS/SSL for connecting to Redis using the `rediss://` protocol. It initializes a `RedisStringsHandler` with specific socket options, including enabling TLS and optionally disabling certificate validation.
```javascript
const { RedisStringsHandler } = require('@trieb.work/nextjs-turbo-redis-cache');
let cachedHandler;
module.exports = class CustomizedCacheHandler {
constructor() {
if (!cachedHandler) {
cachedHandler = new RedisStringsHandler({
redisUrl: 'rediss://your-redis-host:6380', // Note the rediss:// protocol
socketOptions: {
tls: true,
rejectUnauthorized: false, // Only use this if you want to skip certificate validation
},
});
}
}
// ... rest of the handler implementation
};
```
--------------------------------
### Configure Basic Redis Cache Handler (Next.js)
Source: https://context7.com/trieb-work/nextjs-turbo-redis-cache/llms.txt
Sets up the default Redis cache handler for Next.js Cache Components by exporting `redisCacheHandler`. This requires the `@trieb.work/nextjs-turbo-redis-cache` package.
```javascript
// cache-handler.js
const { redisCacheHandler } = require('@trieb.work/nextjs-turbo-redis-cache');
module.exports = redisCacheHandler;
```
```typescript
// next.config.ts
import type { NextConfig } from 'next';
const nextConfig: NextConfig = {
// Enable Cache Components feature
cacheComponents: true,
// Point to the cache handler module
cacheHandlers: {
default: require.resolve('./cache-handler.js'),
},
};
export default nextConfig;
```
--------------------------------
### Enable Redis Key-Space Notifications (Bash)
Source: https://github.com/trieb-work/nextjs-turbo-redis-cache/blob/main/README.md
This command enables Redis key-space notifications for expire and evict events. It's a prerequisite for the cache handler to function correctly with features like intelligent tag management.
```bash
redis-cli -h localhost config set notify-keyspace-events Exe
```
--------------------------------
### Implement Cache Handler Module
Source: https://github.com/trieb-work/nextjs-turbo-redis-cache/blob/main/README.md
Implementation of the cache-handler.js file, supporting both CommonJS and ESM module formats.
```javascript
// CommonJS
const { redisCacheHandler } = require('@trieb.work/nextjs-turbo-redis-cache');
module.exports = redisCacheHandler;
// ESM
import { redisCacheHandler } from '@trieb.work/nextjs-turbo-redis-cache';
export default redisCacheHandler;
```
--------------------------------
### Configure Custom Redis Cache Handler with Options (Next.js)
Source: https://context7.com/trieb-work/nextjs-turbo-redis-cache/llms.txt
Creates a custom Redis cache handler using `getRedisCacheComponentsHandler` for advanced configuration options like Redis URL, database, key prefix, and timeouts. This allows fine-grained control over cache behavior.
```javascript
// cache-handler.js
const { getRedisCacheComponentsHandler } = require('@trieb.work/nextjs-turbo-redis-cache');
const handler = getRedisCacheComponentsHandler({
redisUrl: process.env.REDIS_URL || 'redis://localhost:6379',
database: process.env.NODE_ENV === 'production' ? 0 : 1,
keyPrefix: process.env.VERCEL_URL || 'myapp_',
getTimeoutMs: 500,
revalidateTagQuerySize: 250,
avgResyncIntervalMs: 3600000,
});
module.exports = handler;
```
--------------------------------
### Create Customized Cache Handler Wrapper
Source: https://github.com/trieb-work/nextjs-turbo-redis-cache/blob/main/README.md
Defines a wrapper class for RedisStringsHandler to customize cache behavior such as key prefixes, timeouts, and expiration logic. This class exposes standard cache methods by delegating them to a singleton instance of the Redis handler.
```javascript
const { RedisStringsHandler } = require('@trieb.work/nextjs-turbo-redis-cache');
let cachedHandler;
module.exports = class CustomizedCacheHandler {
constructor() {
if (!cachedHandler) {
cachedHandler = new RedisStringsHandler({
database: 0,
keyPrefix: 'test',
timeoutMs: 2_000,
revalidateTagQuerySize: 500,
sharedTagsKey: '__sharedTags__',
avgResyncIntervalMs: 10_000 * 60,
redisGetDeduplication: false,
inMemoryCachingTime: 0,
defaultStaleAge: 1209600,
estimateExpireAge: (staleAge) => staleAge * 2,
});
}
}
get(...args) {
return cachedHandler.get(...args);
}
set(...args) {
return cachedHandler.set(...args);
}
revalidateTag(...args) {
return cachedHandler.revalidateTag(...args);
}
resetRequestCache(...args) {
return cachedHandler.resetRequestCache(...args);
}
}
```
--------------------------------
### Configure Next.js Cache Handler
Source: https://github.com/trieb-work/nextjs-turbo-redis-cache/blob/main/README.md
Configuration for next.config.ts to enable Cache Components and define the default cache handler module.
```typescript
// next.config.ts
import type { NextConfig } from 'next';
const nextConfig: NextConfig = {
cacheComponents: true,
cacheHandlers: {
default: require.resolve('./cache-handler.js'),
},
};
export default nextConfig;
```
--------------------------------
### Basic Next.js Cache Handler Configuration
Source: https://context7.com/trieb-work/nextjs-turbo-redis-cache/llms.txt
Configures Next.js to use the default Redis cache handler by referencing the package in next.config.js. This enables basic Redis caching functionality.
```javascript
// next.config.js
const nextConfig = {
cacheHandler: require.resolve("@trieb.work/nextjs-turbo-redis-cache"),
};
module.exports = nextConfig;
```
--------------------------------
### Configure Redis Server for Key-Space Notifications
Source: https://context7.com/trieb-work/nextjs-turbo-redis-cache/llms.txt
Enables Redis key-space notifications for 'Expire' and 'Evict' events, which are crucial for automatic cache invalidation when items expire or are removed from Redis. This is done via `redis-cli` commands.
```bash
# Enable key-space notifications for Expire and Evict events
redis-cli -h localhost config set notify-keyspace-events Exe
# Verify the configuration
redis-cli -h localhost config get notify-keyspace-events
# Expected output: 1) "notify-keyspace-events" 2) "Exe"
```
--------------------------------
### Fetch Data with Cache Tags in Next.js
Source: https://context7.com/trieb-work/nextjs-turbo-redis-cache/llms.txt
Demonstrates how to use Next.js fetch caching with tags for granular cache invalidation. This approach allows specific data segments to be revalidated, improving cache management efficiency. It requires Next.js's built-in fetch capabilities.
```typescript
import {
NextResponse
} from 'next/server';
export async function GET() {
// Fetch with caching and tag assignment
const response = await fetch('https://api.example.com/products', {
next: {
// Cache for 15 seconds
revalidate: 15,
// Assign tags for targeted invalidation
tags: ['products', 'catalog'],
},
});
const products = await response.json();
return NextResponse.json({
products,
cachedAt: Date.now(),
});
}
```
--------------------------------
### Customized RedisStringsHandler Configuration in JavaScript
Source: https://context7.com/trieb-work/nextjs-turbo-redis-cache/llms.txt
Creates a customized cache handler wrapper using RedisStringsHandler to configure advanced options like Redis connection details, timeouts, deduplication, and TTL calculations. This allows for fine-grained control over caching behavior.
```javascript
// customized-cache-handler.js
const { RedisStringsHandler } = require('@trieb.work/nextjs-turbo-redis-cache');
let cachedHandler;
module.exports = class CustomizedCacheHandler {
constructor() {
if (!cachedHandler) {
cachedHandler = new RedisStringsHandler({
// Redis connection URL (defaults to REDIS_URL env or redis://localhost:6379)
redisUrl: 'redis://localhost:6379',
// Database number: 0 for production, 1 for other environments
database: 0,
// Prefix for all Redis keys (defaults to VERCEL_URL env)
keyPrefix: 'myapp_',
// Timeout for Redis GET operations (blocks rendering if exceeded)
getTimeoutMs: 500,
// Batch size for tag synchronization queries
revalidateTagQuerySize: 500,
// Key name for shared tags hash map in Redis
sharedTagsKey: '__sharedTags__',
// Interval for full tag map re-synchronization (1 hour default)
avgResyncIntervalMs: 3600000,
// Enable request deduplication to reduce Redis load
redisGetDeduplication: true,
// Duration to cache GET results in memory (0 to disable)
inMemoryCachingTime: 10000,
// Default TTL for cached items (14 days in seconds)
defaultStaleAge: 1209600,
// Function to calculate Redis TTL from stale age
estimateExpireAge: (staleAge) => staleAge * 2,
// Exit process after N consecutive Redis errors (0 to disable)
killContainerOnErrorThreshold: 10,
});
}
}
get(...args) {
return cachedHandler.get(...args);
}
set(...args) {
return cachedHandler.set(...args);
}
revalidateTag(...args) {
return cachedHandler.revalidateTag(...args);
}
resetRequestCache(...args) {
return cachedHandler.resetRequestCache(...args);
}
};
```
```javascript
// next.config.js
const nextConfig = {
cacheHandler: require.resolve("./customized-cache-handler"),
};
module.exports = nextConfig;
```
--------------------------------
### Secure TLS/SSL Redis Connection Configuration in JavaScript
Source: https://context7.com/trieb-work/nextjs-turbo-redis-cache/llms.txt
Configures the Redis cache handler to use TLS/SSL encryption for secure connections. This involves setting the `redisUrl` to `rediss://` and configuring `socketOptions` for TLS.
```javascript
// secure-cache-handler.js
const { RedisStringsHandler } = require('@trieb.work/nextjs-turbo-redis-cache');
let cachedHandler;
module.exports = class SecureCacheHandler {
constructor() {
if (!cachedHandler) {
cachedHandler = new RedisStringsHandler({
// Use rediss:// protocol for TLS connections
redisUrl: 'rediss://your-redis-host:6380',
// TLS socket configuration
socketOptions: {
tls: true,
// Set to false only if using self-signed certificates
rejectUnauthorized: false,
},
// Optional: Redis authentication
clientOptions: {
username: 'your-username',
password: 'your-password',
},
});
}
}
get(...args) {
return cachedHandler.get(...args);
}
set(...args) {
return cachedHandler.set(...args);
}
revalidateTag(...args) {
return cachedHandler.revalidateTag(...args);
}
resetRequestCache(...args) {
return cachedHandler.resetRequestCache(...args);
}
};
```
--------------------------------
### Register Custom Cache Handler in Next.js
Source: https://github.com/trieb-work/nextjs-turbo-redis-cache/blob/main/README.md
Configures the Next.js application to use the custom cache handler by updating the next.config.js file with the path to the wrapper module.
```javascript
const nextConfig = {
...
cacheHandler: require.resolve("./customized-cache-handler")
...
}
```
--------------------------------
### Implement Tag-Based Cache Invalidation API Route (Next.js)
Source: https://context7.com/trieb-work/nextjs-turbo-redis-cache/llms.txt
Provides a Next.js API route (`/api/revalidate`) to invalidate cache entries based on a given tag. It uses the `revalidateTag` function from `next/cache` and expects a JSON payload with a `tag` property.
```typescript
// app/api/revalidate/route.ts
import { NextResponse } from 'next/server';
import { revalidateTag } from 'next/cache';
export async function POST(request: Request) {
const body = await request.json();
const { tag } = body;
if (!tag) {
return NextResponse.json(
{ error: 'Tag is required' },
{ status: 400 }
);
}
// Invalidate all cache entries with this tag
revalidateTag(tag);
return NextResponse.json({
revalidated: true,
tag,
timestamp: Date.now(),
});
}
```
```bash
# Invalidate cache entries tagged with 'products'
curl -X POST http://localhost:3000/api/revalidate \
-H "Content-Type: application/json" \
-d '{"tag": "products"}'
# Expected response:
# {"revalidated":true,"tag":"products","timestamp":1699999999999}
```
--------------------------------
### POST /api/revalidatePath
Source: https://context7.com/trieb-work/nextjs-turbo-redis-cache/llms.txt
Triggers cache invalidation for a specific page path using the Next.js revalidatePath function.
```APIDOC
## POST /api/revalidatePath
### Description
Invalidates the cache for a specific page path.
### Method
POST
### Endpoint
/api/revalidatePath
### Request Body
- **path** (string) - Required - The page path to invalidate.
### Request Example
{
"path": "/products"
}
### Response
#### Success Response (200)
- **revalidated** (boolean) - Confirmation status.
- **path** (string) - The path that was invalidated.
- **timestamp** (number) - Unix timestamp of the operation.
#### Response Example
{
"revalidated": true,
"path": "/products",
"timestamp": 1699999999999
}
```
--------------------------------
### Implement Path-Based Cache Invalidation API Route (Next.js)
Source: https://context7.com/trieb-work/nextjs-turbo-redis-cache/llms.txt
Implements a Next.js API route (`/api/revalidatePath`) for clearing cache entries associated with a specific path. It utilizes the `revalidatePath` function from `next/cache` and requires a JSON payload containing the `path` to invalidate.
```typescript
// app/api/revalidatePath/route.ts
import { NextResponse } from 'next/server';
import { revalidatePath } from 'next/cache';
export async function POST(request: Request) {
const body = await request.json();
const { path } = body;
if (!path) {
return NextResponse.json(
{ error: 'Path is required' },
{ status: 400 }
);
}
// Invalidate cache for the specified path
revalidatePath(path);
return NextResponse.json({
revalidated: true,
path,
timestamp: Date.now(),
});
}
```
```bash
# Invalidate cache for the products page
curl -X POST http://localhost:3000/api/revalidatePath \
-H "Content-Type: application/json" \
-d '{"path": "/products"}'
# Expected response:
# {"revalidated":true,"path":"/products","timestamp":1699999999999}
```
--------------------------------
### POST /api/revalidate
Source: https://context7.com/trieb-work/nextjs-turbo-redis-cache/llms.txt
Triggers cache invalidation for all entries associated with a specific tag using the Next.js revalidateTag function.
```APIDOC
## POST /api/revalidate
### Description
Invalidates all cache entries associated with the provided tag.
### Method
POST
### Endpoint
/api/revalidate
### Request Body
- **tag** (string) - Required - The cache tag to invalidate.
### Request Example
{
"tag": "products"
}
### Response
#### Success Response (200)
- **revalidated** (boolean) - Confirmation status.
- **tag** (string) - The tag that was invalidated.
- **timestamp** (number) - Unix timestamp of the operation.
#### Response Example
{
"revalidated": true,
"tag": "products",
"timestamp": 1699999999999
}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.