Google Antigravity Directory

The #1 directory for Google Antigravity prompts, rules, workflows & MCP servers. Optimized for Gemini 3 agentic development.

Resources

PromptsMCP ServersAntigravity RulesGEMINI.md GuideBest Practices

Company

Submit PromptAntigravityAI.directory

Popular Prompts

Next.js 14 App RouterReact TypeScriptTypeScript AdvancedFastAPI GuideDocker Best Practices

Legal

Privacy PolicyTerms of ServiceContact Us
Featured on FazierFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App ShowAI ToolzShinyLaunchMillion Dot HomepageSolver ToolsFeatured on FazierFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App ShowAI ToolzShinyLaunchMillion Dot HomepageSolver Tools

© 2026 Antigravity AI Directory. All rights reserved.

The #1 directory for Google Antigravity IDE

This website is not affiliated with, endorsed by, or associated with Google LLC. "Google" and "Gemini" are trademarks of Google LLC.

Antigravity AI Directory
PromptsMCPBest PracticesUse CasesLearn
Home
Prompts
Next.js Caching Strategies

Next.js Caching Strategies

Comprehensive caching patterns with revalidation, tags, and on-demand cache invalidation

Next.jsCachingPerformanceApp Router
by Antigravity Team
⭐0Stars
.antigravity
# 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.

When to Use This Prompt

This Next.js prompt is ideal for developers working on:

  • Next.js applications requiring modern best practices and optimal performance
  • Projects that need production-ready Next.js code with proper error handling
  • Teams looking to standardize their next.js development workflow
  • Developers wanting to learn industry-standard Next.js patterns and techniques

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.

How to Use

  1. Copy the prompt - Click the copy button above to copy the entire prompt to your clipboard
  2. Paste into your AI assistant - Use with Claude, ChatGPT, Cursor, or any AI coding tool
  3. Customize as needed - Adjust the prompt based on your specific requirements
  4. Review the output - Always review generated code for security and correctness
💡 Pro Tip: For best results, provide context about your project structure and any specific constraints or preferences you have.

Best Practices

  • ✓ Always review generated code for security vulnerabilities before deploying
  • ✓ Test the Next.js code in a development environment first
  • ✓ Customize the prompt output to match your project's coding standards
  • ✓ Keep your AI assistant's context window in mind for complex requirements
  • ✓ Version control your prompts alongside your code for reproducibility

Frequently Asked Questions

Can I use this Next.js prompt commercially?

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.

Which AI assistants work best with this prompt?

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.

How do I customize this prompt for my specific needs?

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.

Related Prompts

💬 Comments

Loading comments...