Next.jsEasy
How do you fetch data in Server Components (App Router)?
Make the component async and await your data directly: fetch, an ORM, a database client or the file system. Server Components run only on the server, so secrets stay safe and no data-fetching code reaches the browser.
Patterns
- Fetch where the data is used. Each component fetches what it needs; duplicate
fetchcalls with the same URL and options are memoized within one render. Wrap ORM calls inReact.cachefor the same deduplication. - Parallel fetching. Start independent requests together with
Promise.all, or render separate components inside separate<Suspense>boundaries so each streams on its own. - Avoid waterfalls. Awaiting requests one after another in the same component makes total time the sum of all requests.
- Data access layer. Put queries in
server-onlymodules that check authorization, and return only the fields the UI needs.
Caching (Next.js 16)
- With Cache Components, nothing is cached unless you opt in. Add
"use cache"andcacheLifeto a data function or component to cache it and include it in the static shell. Uncached reads must be inside<Suspense>, or the dev overlay reports a blocking route. - Without Cache Components,
fetchis not cached by default since Next.js 15; usecache: 'force-cache'ornext: { revalidate }.
Errors and empty states
Throw to reach the nearest error.tsx, call notFound() for missing data, and return values for expected cases.
Client data
For data that updates after load (polling, infinite scroll), use SWR or TanStack Query in Client Components, optionally seeded with server data.
Code example
tsx
1// app/dashboard/page.tsx2import { Suspense } from "react";3import { cacheLife } from "next/cache";4import { db } from "@/lib/db";56async function getPlans() {7 "use cache"; // same for everyone: part of the static shell8 cacheLife("days");9 return db.plan.findMany();10}1112async function RecentOrders() {13 // Uncached, fresh per request: streams behind Suspense14 const orders = await db.order.findMany({ take: 5, orderBy: { createdAt: "desc" } });15 return <ul>{orders.map((o) => <li key={o.id}>{o.total}</li>)}</ul>;16}1718export default async function Dashboard() {19 const plans = await getPlans();20 return (21 <main>22 <h1>{plans.length} plans</h1>23 <Suspense fallback={<p>Loading orders…</p>}>24 <RecentOrders />25 </Suspense>26 </main>27 );28}
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.