Doc 2
Fetching data
Server Components
You can fetch data in Server Components using any asynchronous I/O, such as:
- The
fetchAPI - An ORM or database
- Reading from the filesystem using Node.js APIs like
fs
With the fetch API
To fetch data with the fetch API, turn your component into an asynchronous function, and await the fetch call. For example:
app/blog/page.tsx
TypeScript
JavaScriptTypeScript
export default async function Page() { const data = await fetch('https://api.vercel.app/blog') const posts = await data.json() return ( <ul> {posts.map((post) => ( <li key={post.id}>{post.title}</li> ))} </ul> )}
Good to know:
fetchresponses are not cached by default. However, Next.js will pre-render the route and the output will be cached for improved performance. If you'd like to opt into dynamic rendering, use the{ cache: 'no-store' }option. See thefetchAPI Reference.- During development, you can log
fetchcalls for better visibility and debugging. See theloggingAPI reference.
With an ORM or database
Since Server Components are rendered on the server, you can safely make database queries using an ORM or database client. Turn your component into an asynchronous function, and await the call:
app/blog/page.tsx
TypeScript
JavaScriptTypeScript
import { db, posts } from '@/lib/db' export default async function Page() { const allPosts = await db.select().from(posts) return ( <ul> {allPosts.map((post) => ( <li key={post.id}>{post.title}</li> ))} </ul> )}
Client Components
There are two ways to fetch data in Client Components, using:
- React's
useAPI - A community library like SWR or React Query
Streaming data with the use API
You can use React's use API to stream data from the server to client. Start by fetching data in your Server component, and pass the promise to your Client Component as prop: