Fetch Data in Next.js Server & Client Components
This guide explains how to fetch data in Next.js App Router, covering both Server Components (default, async) and Client Components (using hooks). You’ll learn the recommended patterns, when to use each, and how to handle loading, errors, and revalidation. You’ll need a Next.js 13+ project with the App Router enabled.
What You’ll Need
- A Next.js project (version 13.4 or later) using the App Router (folder
app/). - Basic familiarity with React components and JavaScript/TypeScript.
- An API endpoint or data source (REST, GraphQL, or a database).
- Node.js installed (v18 or later recommended).
Step-by-Step
- Understand the default: Server Components. In the App Router, all components are Server Components by default. They run on the server, so you can use
asyncandawaitdirectly in the component body. This is the recommended way to fetch data for most pages. - Create a Server Component that fetches data. In your
app/page.tsx(or any server component), make itasyncand use the nativefetchAPI. Next.js extendsfetchwith caching and revalidation options. - Write the fetch call. Example:
export default async function Page() { const res = await fetch('https://api.example.com/posts'); const posts = await res.json(); return ( <ul> {posts.map(post => <li key={post.id}>{post.title}</li>)} </ul> ); } - Add error handling. Wrap the fetch in a try/catch block and return a fallback UI. You can also use the built-in
error.jsfile to catch errors at the route segment level. - Handle loading states. Use the
loading.jsfile in the same folder to show a loading UI (e.g., a spinner) while the server component is fetching data. - Control caching and revalidation. By default,
fetchuses the cache. To revalidate data periodically, add{ next: { revalidate: 60 } }for ISR (incremental static regeneration). To disable caching, use{ cache: 'no-store' }for dynamic data. - For Client Components: mark with “use client”. If you need interactivity (event handlers, useEffect), add
"use client"at the top of the file. Client Components run on the server for initial render, but also on the client. - Fetch data in a Client Component using useEffect. Use the
useEffecthook to fetch data after the component mounts. Example:"use client"; import { useEffect, useState } from 'react'; export default function ClientPosts() { const [posts, setPosts] = useState([]); useEffect(() => { fetch('https://api.example.com/posts') .then(res => res.json()) .then(setPosts); }, []); return <ul>{posts.map(p => <li key={p.id}>{p.title}</li>)}</ul>; } - Use a data fetching library (optional). For client-side fetching with caching and deduplication, consider using SWR or TanStack Query. They provide hooks like
useSWRthat handle loading and error states automatically. - Pass data from Server to Client Components. You can fetch data in a Server Component and pass it as props to a Client Component. This avoids a second fetch and keeps the initial HTML complete.
- Use Route Handlers for custom APIs. If you need a dedicated API endpoint, create a
route.jsfile inapp/api/and export a function likeGET. Then fetch that endpoint from both server and client components. - Test your implementation. Run
npm run devand visit your page. Check the network tab to see the fetch requests and verify caching behavior.
Common Mistakes
- Putting
"use client"at the top of a file that also contains Server Components – this makes all components in that file client-side. - Using
useEffectto fetch data that could be fetched on the server, causing unnecessary loading states and extra requests. - Forgetting to handle errors – an unhandled promise rejection can crash the component.
- Not setting
cache: 'no-store'for data that changes frequently, leading to stale content. - Using
fetchinside a Client Component without handling the loading state, resulting in a flash of empty UI. - Assuming that all
fetchcalls in Server Components are dynamic – by default they are cached.
Tips
- Prefer Server Components for data fetching whenever possible – they reduce client-side JavaScript and improve performance.
- Use parallel data fetching with
Promise.allto speed up multiple independent fetches. - Use the
next/future/imagecomponent to optimize images returned from APIs. - For client-side fetching, use a library like SWR to get built-in caching, revalidation, and mutation support.
- Leverage Next.js’s built-in
notFound()function to trigger a 404 if data is not found. - Use environment variables for API keys and endpoints, never hardcode them.
Troubleshooting
- Data is not showing up: Check the browser console for errors. Ensure the API URL is correct and the server is running. Test the API directly in the browser.
- Component is not updating after fetch: If using
useEffect, make sure the dependency array is correct. If using SWR, check the key for the data. - “use client” error: This directive must be at the very top of the file, before any imports. Move it to the first line.
- Fetch works in dev but not in production: Check if the API is accessible from the server environment. If using a relative URL, it may not resolve in production – use absolute URLs or environment variables.
- Data is stale: If you’re using Server Components, add
{ next: { revalidate: 60 } }or{ cache: 'no-store' }to the fetch call. - Hydration mismatch: This can happen if the server and client render different content. Ensure that client-side fetching happens after mount (in
useEffect) and not during render.
Frequently Asked Questions
Can I use fetch in a Client Component without useEffect?
No, you should use useEffect or a library like SWR. Fetching directly in the component body would run on every render and cause infinite loops.
What’s the difference between Server and Client Components for fetching?
Server Components fetch data once on the server and send the finished HTML to the client. Client Components fetch data in the browser after the page loads, which can cause a brief loading state.
How do I revalidate data fetched in a Server Component?
Use the revalidate option in the fetch call: fetch(url, { next: { revalidate: 60 } }) to revalidate every 60 seconds.
Can I pass fetched data from a Server Component to a Client Component?
Yes, you can pass the data as props. The Client Component will receive it as initial data, and you can still use it for interactivity.
Is it okay to use axios instead of fetch?
Yes, axios works in both Server and Client Components. However, for Server Components, the native fetch is recommended because it integrates with Next.js caching.
How do I handle authentication tokens when fetching?
In Server Components, use cookies or headers to get the token server-side. In Client Components, use the token from context or localStorage, but be aware of security considerations.
Related
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.