Comprehensive caching patterns with revalidation, tags, and on-demand cache invalidation
# Next.js Caching Strategies for Google Antigravity
Optimize performance with Next.js caching using Google Antigravity's Gemini 3 engine. This guide covers fetch caching, route segments, revalidation strategies, and cache invalidation patterns.
## Fetch Caching Options
```typescript
// lib/api.ts
// Cache indefinitely (default for fetch in Server Components)
export async function getStaticData() {
const res = await fetch('https://api.example.com/static-data');
return res.json();
}
// Revalidate every 60 seconds
export async function getProducts() {
const res = await fetch('https://api.example.com/products', {
next: { revalidate: 60 },
});
return res.json();
}
// No caching - always fresh
export async function getCurrentUser() {
const res = await fetch('https://api.example.com/me', {
cache: 'no-store',
});
return res.json();
}
// Cache with tags for targeted invalidation
export async function getProduct(id: string) {
const res = await fetch(`https://api.example.com/products/${id}`, {
next: { tags: ['products', `product-${id}`] },
});
return res.json();
}
// Cache with multiple tags
export async function getCategoryProducts(categoryId: string) {
const res = await fetch(
`https://api.example.com/categories/${categoryId}/products`,
{
next: {
tags: ['products', 'categories', `category-${categoryId}`],
revalidate: 300, // 5 minutes
},
}
);
return res.json();
}
```
## Route Segment Configuration
```typescript
// app/products/page.tsx
// Static generation at build time
export const dynamic = 'force-static';
export const revalidate = 3600; // Revalidate every hour
export default async function ProductsPage() {
const products = await getProducts();
return <ProductList products={products} />;
}
// app/dashboard/page.tsx
// Dynamic rendering, no caching
export const dynamic = 'force-dynamic';
export default async function DashboardPage() {
const user = await getCurrentUser();
return <Dashboard user={user} />;
}
// app/blog/[slug]/page.tsx
// Generate static pages at build time
export async function generateStaticParams() {
const posts = await getPosts();
return posts.map((post) => ({ slug: post.slug }));
}
// Allow dynamic params not generated at build time
export const dynamicParams = true;
export default async function BlogPost({
params,
}: {
params: { slug: string };
}) {
const post = await getPost(params.slug);
return <Article post={post} />;
}
```
## On-Demand Revalidation
```typescript
// app/api/revalidate/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { revalidateTag, revalidatePath } from 'next/cache';
export async function POST(request: NextRequest) {
const authHeader = request.headers.get('authorization');
if (authHeader !== `Bearer ${process.env.REVALIDATION_TOKEN}`) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const { tag, path, type } = await request.json();
try {
if (tag) {
revalidateTag(tag);
return NextResponse.json({ revalidated: true, tag });
}
if (path) {
revalidatePath(path, type);
return NextResponse.json({ revalidated: true, path });
}
return NextResponse.json(
{ error: 'Tag or path required' },
{ status: 400 }
);
} catch (error) {
return NextResponse.json(
{ error: 'Revalidation failed' },
{ status: 500 }
);
}
}
// Webhook handler for CMS updates
// app/api/webhooks/cms/route.ts
import { revalidateTag } from 'next/cache';
export async function POST(request: NextRequest) {
const payload = await request.json();
// Verify webhook signature
const signature = request.headers.get('x-webhook-signature');
if (!verifySignature(payload, signature)) {
return NextResponse.json({ error: 'Invalid signature' }, { status: 401 });
}
// Revalidate based on content type
switch (payload.type) {
case 'post.published':
case 'post.updated':
revalidateTag('posts');
revalidateTag(`post-${payload.data.id}`);
break;
case 'product.updated':
revalidateTag('products');
revalidateTag(`product-${payload.data.id}`);
break;
case 'category.updated':
revalidateTag('categories');
revalidateTag(`category-${payload.data.id}`);
break;
}
return NextResponse.json({ success: true });
}
```
## Custom Cache Implementation
```typescript
// lib/cache.ts
import { unstable_cache } from 'next/cache';
// Cached database query
export const getCachedProducts = unstable_cache(
async (categoryId?: string) => {
return db.product.findMany({
where: categoryId ? { categoryId } : undefined,
include: { category: true },
});
},
['products'],
{
tags: ['products'],
revalidate: 60,
}
);
// Cached user data with dynamic key
export const getCachedUser = (userId: string) =>
unstable_cache(
async () => {
return db.user.findUnique({
where: { id: userId },
include: { profile: true },
});
},
[`user-${userId}`],
{
tags: [`user-${userId}`],
revalidate: 300,
}
)();
// Usage in Server Component
export default async function UserProfile({
params,
}: {
params: { id: string };
}) {
const user = await getCachedUser(params.id);
return <Profile user={user} />;
}
```
## Server Action with Cache Invalidation
```typescript
// app/products/actions.ts
'use server';
import { revalidateTag, revalidatePath } from 'next/cache';
import { db } from '@/lib/db';
export async function updateProduct(id: string, data: ProductData) {
const product = await db.product.update({
where: { id },
data,
});
// Invalidate specific product cache
revalidateTag(`product-${id}`);
// Invalidate products list
revalidateTag('products');
// Invalidate category if changed
if (data.categoryId) {
revalidateTag(`category-${data.categoryId}`);
}
// Revalidate specific paths
revalidatePath(`/products/${id}`);
revalidatePath('/products');
return product;
}
```
## Best Practices
Google Antigravity's Gemini 3 engine recommends these caching patterns: Use cache tags for granular invalidation. Set appropriate revalidation times based on data freshness needs. Implement webhook handlers for instant cache updates. Use unstable_cache for database queries. Monitor cache hit rates and adjust strategies accordingly.This Next.js prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their next.js implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For Next.js projects, consider mentioning your framework version, coding style, and any specific libraries you're using.