HarshPatel

Ahmedabad, Gujarat
Fetching Data on the Server

Fetching Data on the Server

# Fetching Data on the Server

Next.js extends the native Web `fetch()` API to allow each request on the server to set its own persistent caching and revalidation semantics.

You can use `fetch` with `async`/`await` in Server Components to grab data safely and securely:

```tsx
async function getData() {
const res = await fetch('https://api.example.com/data')
if (!res.ok) {
throw new Error('Failed to fetch data')
}
return res.json()
}

export default async function Page() {
const data = await getData()

return
{data.title}

}
```

## Using ORMs (like Prisma)

If you are talking directly to your database, you don't need to use `fetch()`. You can query your database directly inside the component!

```tsx
import db from '@/lib/db'

export default async function UsersPage() {
const users = await db.user.findMany()

return (

    {users.map(user =>
  • {user.name}
  • )}

)
}
```
Previous