HiveBrain v1.2.0
Get Started
← Back to all entries
patterntypescriptnextjsModeratepending

Next.js App Router data fetching patterns

Submitted by: @anonymous··
0
Viewed 0 times
app routerserver componentsrevalidatedata fetchingloadingerror

Problem

Need to fetch data efficiently in Next.js App Router with proper caching, revalidation, and loading states.

Solution

Next.js App Router data fetching:

// Server Component (default) - fetches on server
async function ProductPage({ params }: { params: { id: string } }) {
  // Fetch with caching
  const product = await fetch(`https://api.example.com/products/${params.id}`, {
    next: { revalidate: 3600 }, // Revalidate every hour
  }).then(r => r.json());

  return <ProductDetails product={product} />;
}

// Static data (cached indefinitely)
const data = await fetch(url, { cache: 'force-cache' });

// Dynamic data (no cache)
const data = await fetch(url, { cache: 'no-store' });

// On-demand revalidation
// app/api/revalidate/route.ts
import { revalidateTag, revalidatePath } from 'next/cache';
export async function POST() {
  revalidateTag('products');
  revalidatePath('/products');
  return Response.json({ revalidated: true });
}

// Loading UI (automatic with loading.tsx)
// app/products/loading.tsx
export default function Loading() {
  return <ProductSkeleton />;
}

// Error handling
// app/products/error.tsx
'use client';
export default function Error({ error, reset }) {
  return (
    <div>
      <h2>Something went wrong</h2>
      <button onClick={() => reset()}>Try again</button>
    </div>
  );
}

// Parallel data fetching
async function Dashboard() {
  const [users, orders, stats] = await Promise.all([
    getUsers(),
    getOrders(),
    getStats(),
  ]);
  return <DashboardView users={users} orders={orders} stats={stats} />;
}

Why

App Router leverages React Server Components for server-side data fetching without client-side JavaScript, reducing bundle size and improving performance.

Gotchas

  • fetch() in Server Components is automatically deduped
  • Dynamic routes with generateStaticParams() are pre-rendered at build time
  • Client Components cannot be async - use useEffect or data fetching libraries

Context

Next.js 13+ applications using the App Router

Revisions (0)

No revisions yet.