Cached Fetch with Revalidation
Fetch external data in Server Components with time-based revalidation and error boundaries.
interface Post {
id: number;
title: string;
body: string;
}
export async function getPosts(): Promise<Post[]> {
const res = await fetch('https://jsonplaceholder.typicode.com/posts', {
next: { revalidate: 3600 }, // Cache for 1 hour
});
if (!res.ok) {
throw new Error(`Failed to fetch posts: ${res.status}`);
}
return res.json();
}
// In a Server Component:
// const posts = await getPosts();Use Cases
- CMS content fetching
- API data loading
- Static page hydration
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
On-Demand ISR Revalidation
Trigger incremental static regeneration via API route with secret token validation for instant cache purge.
NextAuth Session Check Pattern
Check authentication status in Server Components and redirect unauthorized users with NextAuth.js.
Server Action with Revalidation
Mutate data with Server Actions and revalidate cached paths or tags for instant UI updates.
useFetch — Generic Data Fetching Hook
Custom React hook for data fetching with loading, error, and refetch states using the Fetch API.