Bolt Data
V0

Command Palette

Search for a command to run...

Doc 2

Fetching data

Server Components

You can fetch data in Server Components using any asynchronous I/O, such as:

  1. The fetch API
  2. An ORM or database
  3. 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:

  • fetch responses 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 the fetch API Reference.
  • During development, you can log fetch calls for better visibility and debugging. See the logging API 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:

  1. React's use API
  2. 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: