typescriptbeginner

Cached Fetch with Revalidation

Fetch external data in Server Components with time-based revalidation and error boundaries.

typescript
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.