CodeBlanks Logo Icon CodeBlanks

Data fetching in RSC

Learn to fetch data directly with async in a server component.

Data fetching in RSC

In Server Components you write an async function and use await fetch(). Since the request runs on the server, the API key never leaks to the client.

Next.js caches fetch calls; requesting the same data again returns from the cache. Use cache: 'no-store' for dynamic data and next: { revalidate: 60 } for 60 second revalidation.

Data fetching is now done directly in the component, not with useEffect.

Cache and revalidation

Next.js automatically caches fetch calls. Requests to the same URL merge into one; this is called request memoization.

The data cache is per URL; when the revalidate period expires the data is re-fetched in the background. The old data is shown immediately and replaced when the new data is ready.

This gives both a fast first render and fresh data.

Practice Write the UserProfile server component

Write a UserProfile server component. Take an id prop. Make it an async function. Fetch with await fetch(`https://api.example.com/users/${id}`) and parse with res.json(). Return <h1>{user.name}</h1>. Export it.

Starter code

App.jsx
// Write the UserProfile server component here

Sample solution

App.jsx
async function UserProfile({ id }) {
  const res = await fetch(`https://api.example.com/users/${id}`);
  const user = await res.json();
  return <h1>{user.name}</h1>;
}
export default UserProfile;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match fetch options

Term Meaning
cache: 'no-store' Dynamic data
next: revalidate: 60 Refresh every 60 s
await fetch Waits on server
res.json() Parse to JSON

2 How is data fetched in RSC?

  • With fetch inside useEffect
  • With addEventListener
  • With setInterval
  • With await fetch in an async component Correct answer

Explanation: Server components use await fetch as async functions.

3 Fill in the blank: dynamic data

Question
const res = await fetch('/api/news', { cache: '____' });
Answer
const res = await fetch('/api/news', { cache: 'no-store' });

Explanation: cache: 'no-store' gives fresh data every request.

All lessons in Expert