The previous module ended with a protected data layer: server-only, validated environment variables and a clear rule about what crosses into the browser. But on the inside that layer is still an array with an artificial pause. In this module it becomes a real data layer.
We'll start with the source you control least, an external API. AgendaViva will show the weather forecast for outdoor events. Requesting it takes two lines; what this lesson is about is everything else: what to do if it's slow, if it fails, if it returns something unexpected or if it doesn't have the data, where to put that code and why it shouldn't go through an endpoint of your own. Caching is left for module 5: for now, every visit makes its own request.
- Fetching data where it's used
A Server Component can be async, so reading data means awaiting a promise in the component itself. There's no loading state to manage, no effect and no library. Compare the two paths for the same data:
useEffect and fetch in the browser |
await in a Server Component |
|
|---|---|---|
| When the request starts | After downloading, hydrating and running the effect | As soon as it renders |
| Who talks to the API | The visitor's browser | Your server |
| Access keys | Exposed | Stay on the server |
| CORS | Can block it | Doesn't come into play |
| Loading and error state | State variables | <Suspense> and error boundaries |
| What reaches the browser | The API's full response | Only what you render |
You can await any asynchronous operation: a fetch, an ORM query, reading a file. It makes no difference to the component, and that's why functions returning promises were enough in 01-04.
AgendaViva's rule doesn't change: components don't call fetch or the ORM; they call a function in lib/data/. Each layer answers one question:
| Layer | Question it answers | What it doesn't know |
|---|---|---|
lib/data/ |
Where the data comes from, under what rules and in what shape | How it's rendered |
async component |
What data is needed here and what to show if it's missing | Where it comes from |
| Presentational component | How it looks | That the data was asynchronous |
<Suspense> and ErrorBoundary |
What's shown in the meantime or if something breaks | What the data is |
- The new data: the forecast
The forecast only matters for open-air spaces, so the venue has to know whether it is one. Add the field to the type:
In lib/data/memory.ts, add outdoor: false to the three existing venues, create a fourth one and move "River Tales" there:
// lib/data/memory.ts, at the end of the venues array
{ id: 'ven-04', slug: 'grove-park', name: 'Grove Park', district: 'Riverside',
address: 'Grove Walk', capacity: 400, outdoor: true },
// and in event evt-07
venueId: 'ven-04',2.1. A fake API with real failures
We'll use a fictitious service, https://api.weather.example, which requires a key and responds with JSON. The .example domain is reserved for documentation and doesn't exist, so during development a small Node server will stand in for it. Besides not depending on anyone, it lets you trigger failures at will, something no provider offers:
// scripts/weather-api.mjs — simulates the external API during development
import { createServer } from 'node:http'
const DELAY = Number(process.env.DELAY ?? 400)
const FAILURE = process.env.FAILURE ?? ''
const server = createServer(async (request, response) => {
const url = new URL(request.url ?? '/', 'http://localhost')
const day = url.searchParams.get('day') ?? ''
console.log(request.method, url.pathname + url.search)
function send(status, body) {
response.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8' })
response.end(JSON.stringify(body))
}
await new Promise((resolve) => setTimeout(resolve, DELAY))
if (url.pathname !== '/v1/forecast') return send(404, { error: 'unknown path' })
if (request.headers.authorization !== 'Bearer dev-key') {
return send(401, { error: 'invalid key' })
}
if (FAILURE === '500') return send(500, { error: 'simulated outage' })
if (FAILURE === 'format') return send(200, { high: 'twenty-four' })
if (FAILURE === 'no-data') return send(404, { error: 'day out of range' })
if (!/^\d{4}-\d{2}-\d{2}$/.test(day)) return send(400, { error: 'invalid day' })
send(200, { day, sky: 'clouds', low: 14, high: 24, rain: 30 })
})
server.listen(4000, () => console.log('Weather API at http://localhost:4000'))node scripts/weather-api.mjs # normal operation
DELAY=8000 node scripts/weather-api.mjs # doesn't answer in time
FAILURE=500 node scripts/weather-api.mjs # service error
FAILURE=format node scripts/weather-api.mjs # response with a different shape
FAILURE=no-data node scripts/weather-api.mjs # no forecast for that dayLeave it running in another terminal. The address and the key are configuration, so they go in the environment:
# .env.local (add the same keys, with a comment, to .env.example)
WEATHER_URL=http://localhost:4000
WEATHER_KEY=dev-key// lib/env.ts: new fields in Env…
weatherUrl: string | null
weatherKey: string | null
// …and in the object readEnv returns
weatherUrl: process.env.WEATHER_URL?.trim() || null,
weatherKey: process.env.WEATHER_KEY?.trim() || null,They're optional: the guide must start even if nobody has signed up for the weather service.
- The naive version
This code works as long as everything goes well:
async function DayForecast({ day }: { day: string }) {
const response = await fetch(
`${process.env.WEATHER_URL}/v1/forecast?day=${day}&key=${process.env.WEATHER_KEY}`,
)
const forecast = await response.json()
return <p>High of {forecast.high} degrees</p>
}It has six flaws, and each of the following sections fixes some of them:
| Flaw | Consequence |
|---|---|
It doesn't check response.ok |
fetch does not reject on a 404 or a 500; it renders "High of undefined degrees" |
| No time limit | If the API hangs, the response to the visitor stays open until something cuts it off |
json() returns any |
TypeScript stops checking anything from that point on |
| It trusts the shape of the JSON | A change on the provider's side breaks the page or shows nonsense |
| The key goes in the URL | It shows up in your server's logs and in the provider's |
| The component knows about the API | Switching providers means touching the UI |
- The data function
4.1. What it returns: a value for each outcome
In 02-04 we separated the expected, which is returned, from the unexpected, which is thrown. The events query failing is unexpected: without it there's no page. A third-party service failing, on the other hand, is only a matter of time, and the event page is still useful without the forecast. The deciding question is: can the UI do something sensible without the data? If the answer is yes, the failure is just another value.
A discriminated union forces the caller to consider every case:
// lib/types.ts (addition)
export const SKIES = ['sun', 'clouds', 'rain', 'storm', 'snow'] as const
export type Sky = (typeof SKIES)[number]
export interface Forecast {
sky: Sky
low: number
high: number
rain: number // Probability, from 0 to 100
}
export type ForecastResult =
| { status: 'available'; forecast: Forecast }
| { status: 'no-data' }
| { status: 'error' }Forecast is our type, not a copy of the provider's JSON. If tomorrow the service calls the high temp_max, the conversion will change and nothing else.
4.2. Validating the response
Whatever arrives over the network is unknown. Writing as Forecast would make it compile without checking anything; it's the same mistake as as Category in 02-02. A function turns the unknown value into a reliable one, or returns null:
// lib/data/weather.ts
import 'server-only'
import { io } from 'next/cache'
import { readEnv } from '@/lib/env'
import { SKIES, type Sky, type Forecast, type ForecastResult } from '@/lib/types'
const TIMEOUT_MS = 2500
function isSky(value: unknown): value is Sky {
return SKIES.some((sky) => sky === value)
}
function isNumber(value: unknown): value is number {
return typeof value === 'number' && Number.isFinite(value)
}
// Converts the provider's JSON into our type, or returns null if it doesn't fit
function parseForecast(data: unknown): Forecast | null {
if (typeof data !== 'object' || data === null) return null
const { sky, low, high, rain } = data as Record<string, unknown>
if (!isSky(sky) || !isNumber(low) || !isNumber(high) || !isNumber(rain)) {
return null
}
return { sky, low, high, rain }
}The only as left is harmless: Record<string, unknown> doesn't claim anything about the values, it only lets you read them. Each one is then required to pass its check. In 06-03 you'll do the same with a Zod schema, which takes less code and explains better what failed; the idea doesn't change.
You validate what you use, not everything that arrives. If the provider adds fields, nothing happens; if it removes one of ours, we'll find out here and not in the UI.
4.3. Requesting with a time limit
// lib/data/weather.ts (continued)
async function requestForecast(
url: URL,
key: string,
): Promise<ForecastResult> {
const response = await fetch(url, {
headers: { Authorization: `Bearer ${key}`, Accept: 'application/json' },
signal: AbortSignal.timeout(TIMEOUT_MS),
})
if (response.status === 404) return { status: 'no-data' }
if (!response.ok) throw new Error(`The weather API responded with ${response.status}`)
const forecast = parseForecast(await response.json())
if (!forecast) throw new Error('The weather API returned an unknown format')
return { status: 'available', forecast }
}
// day in YYYY-MM-DD format
export async function getForecast(day: string): Promise<ForecastResult> {
await io()
const { weatherUrl, weatherKey } = readEnv()
if (!weatherUrl || !weatherKey) return { status: 'no-data' }
const url = new URL('/v1/forecast', weatherUrl)
url.searchParams.set('day', day)
try {
return await requestForecast(url, weatherKey)
} catch (error) {
console.error('Could not get the forecast:', error)
return { status: 'error' }
}
}Piece by piece:
AbortSignal.timeout(2500)creates a signal that fires on its own. If it expires,fetchrejects with an error namedTimeoutError. It also covers reading the body: a server that sends the headers and then goes silent gets cut off too. Without a signal, the time limit is up to Node's HTTP client, which is very generous.- Two and a half seconds is a product decision. Meanwhile there's a hole in the page, and no visitor will wait longer for a secondary piece of data.
- The URL is built with
URLandsearchParams, which encode. The origin always comes from configuration: if any part of the target server depended on what the user types, they could make your server call internal addresses. - The key travels in a header.
- The 404 means "no data" in this API, and it's distinguished from an outage. Every provider has its own conventions; read them before translating them.
json()can also reject if the body isn't JSON. The samecatchhandles it.- The error is logged in full, but it doesn't leave the function.
requestForecastthrows freely and a single place decides. The caller gets a status without internal details. await io()is outside thetry. During prerendering that promise never resolves: it's how Next.js stops the component. Wrapping it in atry/catchwould mix that mechanism with your errors. It also plays the role you saw in 03-05: environment variables are read during the request, not at build time.
Notice what isn't there: retries. During a render, retrying multiplies the visitor's wait. They make sense in background processes, like the ones in 07-03.
- Showing it on the event page
The API wants the day as YYYY-MM-DD in the event's time zone. toISOString() would give the day in UTC, which near midnight is a different one:
// lib/format.ts (addition; also imports the Sky type)
const dayParts = new Intl.DateTimeFormat('en', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
timeZone: 'Europe/Madrid',
})
export function formatIsoDay(date: Date): string {
const parts = Object.fromEntries(
dayParts.formatToParts(date).map(({ type, value }) => [type, value]),
)
return `${parts.year}-${parts.month}-${parts.day}`
}
export const SKY_LABELS: Record<Sky, string> = {
sun: 'Sunny',
clouds: 'Cloudy',
rain: 'Rain',
storm: 'Storm',
snow: 'Snow',
}// app/(public)/events/_components/day-forecast.tsx
import { getForecast } from '@/lib/data/weather'
import { SKY_LABELS, formatIsoDay } from '@/lib/format'
export async function DayForecast({ date }: { date: Date }) {
const result = await getForecast(formatIsoDay(date))
if (result.status === 'no-data') return null
if (result.status === 'error') {
return <p className="text-sm text-slate-600">The forecast isn't available right now.</p>
}
const { sky, low, high, rain } = result.forecast
return (
<p className="text-sm">
Outdoor event. Forecast: {SKY_LABELS[sky].toLowerCase()}, between{' '}
{low} and {high} degrees, {rain}% chance of rain.
</p>
)
}After the first two checks, TypeScript knows that result can only be available and lets you read forecast. If a case were forgotten, it wouldn't compile. That's the advantage over a Forecast | null, which can't tell "there isn't any" apart from "it isn't working".
The one that knows whether the venue is outdoors is EventLocation. It now receives the date as well:
// app/(public)/events/_components/event-details.tsx
async function EventLocation({ venueId, date }: { venueId: string; date: Date }) {
const venue = await getVenueById(venueId)
if (!venue) return null
return (
<>
<p>
<Link href={`/venues/${venue.slug}`} className="underline">
{venue.name}
</Link>
, {venue.address} ({venue.district})
</p>
{venue.outdoor && (
<Suspense fallback={<p className="text-sm">Checking the forecast…</p>}>
<DayForecast date={date} />
</Suspense>
)}
</>
)
}
// In EventDetails
<EventLocation venueId={event.venueId} date={event.startsAt} />Open /events/river-tales and you'll see three steps: the event page, the location and the forecast. Each one waits for the previous one, because the venue depends on the event and the forecast on the venue. It's a waterfall; we'll shorten it in 04-03.
Now go through the failures from section 2.1, restarting the API with each variant:
| API | What you see | Next.js terminal |
|---|---|---|
| Normal | The forecast | |
| Stopped | "Isn't available" right away | fetch failed, with ECONNREFUSED as the cause |
DELAY=8000 |
The notice, after 2.5 seconds | TimeoutError |
FAILURE=500 |
The notice | "responded with 500" |
FAILURE=format |
The notice | "unknown format" |
FAILURE=no-data |
Nothing |
In no case is the event page lost, and in no case does the rest of the page wait.
- Repeated requests within a single render
If two components request the same thing during a render, are two requests made? Next.js memoizes GET fetch calls with the same URL and the same options: the first one goes out to the network and the others receive its result. It applies to layouts, pages and any Server Component in the tree, and lasts as long as that render does. It isn't a cache: the next visit requests again.
fetch memoization |
Cache (module 5) | |
|---|---|---|
| Duration | One render | Whatever you specify |
| Shared between visits | No | Yes |
| How it's enabled | Automatically | With 'use cache' |
| Works in a Route Handler | No: it isn't part of the React tree | Yes |
There's an exception that affects us directly: passing a signal disables memoization. The Next.js documentation says so, and it makes sense, because canceling a shared request would affect the others. In other words, our time limit gives up memoization. It doesn't matter right now, because the forecast appears once per page. To get it back without losing the time limit, you wrap the function in React.cache, which also works for database queries, where there's no fetch. We'll do that in 04-03.
With Cache Components, fetch doesn't store anything between requests by default. Online you'll see options like cache: 'force-cache' or next: { revalidate: 3600 }; they mostly belong to the previous model, covered in 05-06.
6.1. Watching requests in development
To see which fetch calls are made, enable logging in the configuration:
It only works in development. Keep in mind another quirk of that mode: when you save a file, Fast Refresh reuses the fetch responses it already has, so it doesn't spend calls on every change. If you've just restarted the API with a different failure and don't see the effect, reload the page, which does discard them.
- Don't call your own API from the server
People coming from the API-plus-SPA model often create an /api/events endpoint and read it from the page. In a Server Component that's a detour:
// Unnecessary, and it also fails at build time if prerendered
async function EventList() {
const response = await fetch('http://localhost:3000/api/events')
const events = await response.json()
// …
}flowchart LR
subgraph R["With a detour"]
A["Server Component"] -- "HTTP, JSON" --> B["Route Handler"] --> C["listEvents"] --> D[("Data")]
end
subgraph X["Direct"]
E["Server Component"] --> F["listEvents"] --> G[("Data")]
end
- It's an extra network request, with its serialization, between two pieces that are already in the same process.
- It needs an absolute URL, which changes in every environment.
- At build time there's no server listening: if the component is prerendered, the request fails.
- Types and data are lost. Dates arrive as strings and
json()returnsany. - The original request is lost. The visitor's cookies aren't forwarded to that second request automatically, so the session disappears.
The solution isn't to duplicate code: it's for the Server Component and the Route Handler to call the same function in lib/data/. Route Handlers exist for whoever is outside: the browser (04-06), a mobile app or a third party (07-01).
Common Mistakes and Tips
- Assuming
fetchfails on a 500. It only rejects if there's no response. Checkok. - Not setting a time limit. The slowest provider decides how long your page takes.
- Typing the response with
as. The type becomes a promise nobody keeps. Validate. - Returning an empty list or a zero when something fails. "0% chance of rain" because of an outage is false information.
- Using exceptions for secondary data without an error boundary nearby: it takes the page down with it.
- Putting
io(),notFound()orredirect()inside atry/catch. They're signals for Next.js, not errors. - Putting the key in the URL, or building the target domain from user data.
- Expecting memoization to be a cache, or to work with
signal.
Exercises
Exercise 1: classifying failures
For each situation, decide whether the data function should return a value or throw, and what will be shown: (a) a slug that doesn't exist; (b) the database doesn't respond when the guide is requested; (c) an external ratings service takes too long and only adds stars to the event page; (d) the service that confirms whether there are spots left doesn't answer while someone is booking.
Solution
- (a) A value:
null. The page turns it intonotFound(). - (b) An exception. Without events there's nothing to show;
ErrorBoundarycatches it and offers a retry. - (c) A value, with an error status. The event page is useful without stars: they're left out or a discreet text is shown.
- (d) A value with a message for the user, and the booking is not confirmed. It isn't secondary, but it isn't a programming error either: whoever is booking needs to know they can try again. When in doubt, a write takes the safe option.
Exercise 2: rain warnings
For outdoor events, if the chance of rain is 60% or more, the page must show "Check for possible venue changes". Where would you put the 60% rule? Implement it without the component knowing the number.
Solution
// lib/data/weather.ts
const RAIN_RISK_THRESHOLD = 60
export function hasRainRisk(forecast: Forecast): boolean {
return forecast.rain >= RAIN_RISK_THRESHOLD
}// day-forecast.tsx, after the first paragraph (wrap both in a fragment)
{hasRainRisk(result.forecast) && (
<p className="text-sm font-medium">Check for possible venue changes.</p>
)}It's a business rule, not a presentation one: tomorrow the organizer dashboard might use it too. In lib/data/ it lives in a single place. Try it by changing rain: 30 to 80 in the simulated API. The course doesn't keep it.
Exercise 3: reviewing a data function
Find the problems in this function, which shows the river level, and rewrite it.
export async function riverLevel(station: string) {
try {
const r = await fetch('https://rivers.example.com/' + station, { cache: 'force-cache' })
const data = (await r.json()) as { level: number }
return data.level
} catch {
return 0
}
}Solution
- It doesn't check
okor validate: a 500 with JSON would returnundefinedas if it were a number. - It turns the failure into
0, a false figure that's also reassuring when the river is in flood. - It swallows the error without logging it, has no time limit and has no
server-only. stationis concatenated without encoding: with../it would change the path.- It stores the response with an option from the previous model and with no expiry. Here it's always requested.
import 'server-only'
export async function riverLevel(station: string): Promise<number | null> {
const url = new URL(encodeURIComponent(station), 'https://rivers.example.com/')
try {
const response = await fetch(url, { signal: AbortSignal.timeout(2500) })
if (!response.ok) throw new Error(`Response ${response.status}`)
const data: unknown = await response.json()
if (
typeof data === 'object' &&
data !== null &&
'level' in data &&
typeof data.level === 'number'
) {
return data.level
}
throw new Error('Unknown format')
} catch (error) {
console.error('Could not read the river level:', error)
return null
}
}Here null is enough because there's only one reason not to have the data. JavaScript's in lets TypeScript narrow data without any as. In the project you'd add await io() before the try, as in getForecast.
Conclusion
Reading data on the server means awaiting a promise in the component that needs it, and the work lies in what surrounds it: a time limit, checking ok, validating what you receive and a result that tells "there isn't any" apart from "it isn't working". All of that lives in lib/data/, equally within reach of components and endpoints, without going through HTTP. fetch memoization avoids repeated requests within a render, unless you use signal.
The data layer now talks to the outside world, but the events are still in an array that's lost on restart. In the next lesson, Database Access with an ORM, they'll move to PostgreSQL with Drizzle without the pages changing a single line.
