Fetching data in server components lets your app get information before showing the page. This makes pages load faster and work better for users.
0
0
Fetch in server components in NextJS
Introduction
You want to get data from an API before showing the page.
You need to load content from a database on the server side.
You want to keep API keys safe by fetching data only on the server.
You want to improve page speed by sending ready data to the browser.
You want to avoid loading spinners by fetching data before rendering.
Syntax
NextJS
export default async function Page() { const res = await fetch('https://api.example.com/data'); const data = await res.json(); return ( <main> <h1>Data:</h1> <pre>{JSON.stringify(data, null, 2)}</pre> </main> ); }
Use await fetch() inside an async server component function.
Server components run only on the server, so you can safely fetch data here.
Examples
Fetch a list of users and show how many were found.
NextJS
export default async function Page() { const res = await fetch('https://api.example.com/users'); const users = await res.json(); return <div>{users.length} users found</div>; }
Fetch posts and display their titles in a list.
NextJS
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> ); }
Fetch data without caching to always get fresh results.
NextJS
export default async function Page() { const res = await fetch('https://api.example.com/data', { cache: 'no-store' }); const data = await res.json(); return <div>Fresh data loaded every time</div>; }
Sample Program
This server component fetches a todo item from a public API and shows its title and completion status.
NextJS
export default async function Page() { const res = await fetch('https://jsonplaceholder.typicode.com/todos/1'); const todo = await res.json(); return ( <main> <h1>Todo Item</h1> <p><strong>Title:</strong> {todo.title}</p> <p><strong>Completed:</strong> {todo.completed ? 'Yes' : 'No'}</p> </main> ); }
OutputSuccess
Important Notes
Server components run only on the server, so you cannot use browser-only APIs here.
Use cache: 'no-store' in fetch options to disable caching if you want fresh data every time.
Fetching in server components helps keep API keys safe because code does not run in the browser.
Summary
Fetch data inside async server components using await fetch().
Server components run on the server, so data is ready before the page shows.
This improves speed and security by keeping data fetching away from the browser.