Next.js
Beginner
1 min read
Caching, Revalidation, and Streaming
Example
// On-demand revalidation in a Route Handler
// app/api/revalidate/route.ts
import { revalidatePath, revalidateTag } from 'next/cache';
import { NextRequest, NextResponse } from 'next/server';
export async function POST(request: NextRequest) {
const secret = request.headers.get('x-revalidate-secret');
if (secret !== process.env.REVALIDATE_SECRET) {
return NextResponse.json({ error: 'Invalid token' }, { status: 401 });
}
const { path, tag } = await request.json();
if (tag) {
revalidateTag(tag); // purge all entries with this tag
} else if (path) {
revalidatePath(path); // purge a specific path
}
return NextResponse.json({ revalidated: true });
}
// Tagging fetch calls for targeted invalidation
// app/products/page.tsx
async function getProducts() {
const res = await fetch('https://api.example.com/products', {
next: {
tags: ['products'], // tag this cache entry
revalidate: 3600,
},
});
return res.json();
}
// Streaming with Suspense
// app/page.tsx
import { Suspense } from 'react';
import SlowWidget from './SlowWidget';
export default function Home() {
return (
<main>
<h1>Dashboard</h1>
<Suspense fallback={<p>Loading widget...</p>}>
<SlowWidget />
</Suspense>
</main>
);
}