How do you fetch data inside a server component in the App Router?
Short answer
You can simply use async and await directly inside a server component's function body, calling fetch or a database query, since server components run on the server and can handle asynchronous operations naturally before the page is sent to the browser.
Advertisement
AModel answer
You can simply use async and await directly inside a server component's function body, calling fetch or a database query, since server components run on the server and can handle asynchronous operations naturally before the page is sent to the browser.
export default async function Page() {
const res = await fetch('https://api.example.com/posts');
const posts = await res.json();
return <ul>{posts.map(p => <li key={p.id}>{p.title}</li>)}</ul>;
}Real-world example
A blog homepage fetches its list of articles directly inside the page component, rendering the full list of posts as static HTML before it ever reaches the visitor's browser.
Likely follow-ups
- Do you need any special hooks to fetch data in a server component?
- How is this different from fetching data in the Pages Router?
Related topics