Data fetching in server components lets your app get data before showing the page. This makes pages load faster and work better for users.
0
0
Data fetching in server components in NextJS
Introduction
When you want to load data from a database or API before showing the page.
When you want to keep your page fast by doing data work on the server.
When you want to avoid loading spinners by having data ready when the page shows.
When you want to keep secrets like API keys safe on the server side.
When you want to improve SEO by sending fully loaded pages to search engines.
Syntax
NextJS
export default async function Page() { const data = await fetch('https://api.example.com/data').then(res => res.json()) return ( <main> <h1>Data:</h1> <pre>{JSON.stringify(data, null, 2)}</pre> </main> ) }
Server components can use await directly because they run on the server.
Use fetch inside server components to get data before rendering.
Examples
Fetch user data and show the user's name.
NextJS
export default async function UserProfile() { const user = await fetch('https://api.example.com/user').then(res => res.json()) return <div>{user.name}</div> }
Fetch a list of posts and display their titles in a list.
NextJS
export default async function Posts() { const posts = await fetch('https://api.example.com/posts').then(res => res.json()) return ( <ul> {posts.map(post => <li key={post.id}>{post.title}</li>)} </ul> ) }
Fetch data without caching to always get fresh data.
NextJS
export default async function Page() { const data = await fetch('https://api.example.com/data', { cache: 'no-store' }).then(res => res.json()) return <pre>{JSON.stringify(data)}</pre> }
Sample Program
This server component fetches current weather data for London from a weather API and shows the temperature and condition.
NextJS
export default async function Weather() { const response = await fetch('https://api.weatherapi.com/v1/current.json?key=demo&q=London') const weather = await response.json() return ( <main> <h1>Weather in {weather.location.name}</h1> <p>Temperature: {weather.current.temp_c}°C</p> <p>Condition: {weather.current.condition.text}</p> </main> ) }
OutputSuccess
Important Notes
Server components run only on the server, so you can safely use secrets like API keys here.
Data fetching in server components happens before the page is sent to the browser, so users see content immediately.
Use cache: 'no-store' in fetch options if you want fresh data every time.
Summary
Server components fetch data before rendering to improve speed and SEO.
You can use await fetch() directly inside server components.
This keeps your API keys safe and your pages fast.