This whole module has read data on the server, at render time. It's the default path and will remain so. But a rendered page is a snapshot: if someone books the last three spots while another person is reading the event page, that person's screen will still say "3 spots left". And some data can't be requested in advance, because it depends on what's being typed.
In those cases, the browser asks. This lesson defines when that's needed, shows why a useEffect with fetch is harder than it looks, and uses a library, SWR, for two AgendaViva features: spots left that update on their own and search suggestions. The project's first Route Handlers will appear, minimal ones, along with the most important question: how to do this without going back to the SPA from 01-01.
- When the browser should ask
| Situation | Browser? | Reason |
|---|---|---|
| Data for the first load | No | Server Component: it arrives in the HTML |
| Filters and pagination in the URL | No | A navigation requests them from the server (02-02) |
| Data shown after an action | No | The Server Action returns the new UI (module 6) |
| Slow data for an interactive component | No | Promise and use (03-03) |
| Data that changes while the page is open | Yes | Polling: spots left, a scoreboard |
| Data that depends on what's being typed | Yes | Autocomplete, checking whether a name is available |
| More items on scroll | Yes | Infinite scrolling |
| Data from a browser API | Yes | Geolocation, clipboard |
| The same query, shared by many client components that refresh it | Yes | Client-side cache |
The question that separates them is: is the data needed once, or does it stay alive after the page has rendered? For the former, the server. Before moving on to the latter, check whether a promise with use is enough, since it needs neither an endpoint nor a library:
Promise and use |
Client-side data library | |
|---|---|---|
| Who starts the query | The server, at render time | The browser, after hydrating |
| Updates on its own | No | Yes: polling, focus, reconnection |
| Needs an endpoint | No | Yes |
| Code shipped | Nothing extra | The library |
- The direct path and its holes
This component suggests events as you type. It's what you'd write on the first attempt:
'use client'
function Suggestions({ text }: { text: string }) {
const [results, setResults] = useState<Suggestion[]>([])
useEffect(() => {
fetch(`/api/suggestions?q=${text}`)
.then((response) => response.json())
.then(setResults)
}, [text])
return <SuggestionList results={results} />
}The flaws are those from 04-01 (it doesn't check ok, doesn't encode, doesn't handle errors) plus one specific to the browser: the race condition. Every keystroke sends a request, and nothing guarantees the responses arrive in order:
sequenceDiagram
participant U as Component
participant S as Server
U->>S: q=wo
U->>S: q=workshop
S-->>U: results for workshop
S-->>U: results for wo (slower)
Note over U: "wo" is shown with "workshop" typed
The cure is for the effect to cancel its request when it's no longer the current one:
useEffect(() => {
const controller = new AbortController()
async function search() {
try {
const response = await fetch(`/api/suggestions?q=${encodeURIComponent(text)}`, {
signal: controller.signal,
})
if (!response.ok) throw new Error(`Response ${response.status}`)
setResults(await response.json())
} catch (error) {
if (controller.signal.aborted) return // The effect itself canceled it
setError(error)
}
}
search()
return () => controller.abort()
}, [text])The cleanup function runs before the next effect and on unmount. The previous request is aborted, its promise rejects and is ignored. Now it's correct, and there's still the loading state, not requesting on every key, reusing what's already been fetched, retrying, and not repeating the request if two components want the same thing. It's a problem that's been solved many times; that's why libraries exist.
- SWR
The two most widely used are SWR and TanStack Query. Both do essentially the same thing: a cache in the browser, indexed by a key, that knows when to refresh itself.
| SWR | TanStack Query | |
|---|---|---|
| API | One hook, useSWR(key, fn) |
useQuery, useMutation, QueryClient |
| Key | Usually the URL | An array |
| Initial data from the server | fallbackData or <SWRConfig fallback> |
HydrationBoundary |
| Freshness | Always considered stale and revalidated | Configurable staleTime |
| Mutations, dependencies between queries | Basic | Very complete |
| A good fit for | A few live reads | Applications with a lot of remote state on the client |
AgendaViva reads almost everything on the server and only needs two live reads, so we chose SWR for its small size. With a dashboard full of tables that are constantly being edited, TanStack Query would be a reasonable choice.
The name is the strategy, stale-while-revalidate: it first returns what it has, even if it's old, requests the new data and updates. The function that fetches the data is ours and works for everything:
// lib/http-client.ts
import 'client-only'
export class HttpError extends Error {
status: number
constructor(status: number) {
super(`Response ${status}`)
this.status = status
}
}
export async function fetchJson<T>(url: string): Promise<T> {
const response = await fetch(url, { headers: { Accept: 'application/json' } })
if (!response.ok) throw new HttpError(response.status)
return response.json()
}It must throw if the response isn't successful. SWR treats whatever rejects as a failure; if you returned the JSON of a 500, it would store it as valid data.
Here T is accepted without validation, unlike in 04-01. The difference is who's on the other end: this endpoint is ours, lives in the same repository and shares the types. Even so, remember that JSON has no dates: a Date would arrive as a string even though the type says otherwise. The objects in this lesson only contain strings and numbers, on purpose.
- Spots, live
4.1. The data and the endpoint
// lib/types.ts (addition)
export type Availability = Pick<AgendaEvent, 'spotsLeft' | 'capacity'>
export type Suggestion = Pick<AgendaEvent, 'slug' | 'title'>// lib/data/events.ts (addition)
export async function getAvailability(slug: string): Promise<Availability | null> {
const db = await getDb()
const [availability] = await db
.select({ spotsLeft: events.spotsLeft, capacity: events.capacity })
.from(events)
.where(and(eq(events.slug, slug), isPublished))
.limit(1)
return availability ?? null
}// app/api/events/[slug]/availability/route.ts
import { getAvailability } from '@/lib/data/events'
export async function GET(
_request: Request,
{ params }: RouteContext<'/api/events/[slug]/availability'>,
) {
const { slug } = await params
const availability = await getAvailability(slug)
if (!availability) return Response.json({ error: 'Event not found' }, { status: 404 })
return Response.json(availability, { headers: { 'Cache-Control': 'no-store' } })
}A route.ts file publishes an endpoint at its folder's URL, with one function per HTTP method. They're covered in depth in 07-01; for now, four observations:
- It contains no logic. It translates a request into a call to
lib/data/and its result into HTTP. The "published only" rule is in a single place. - Here a 404 is a real 404. There's no shell that has already gone out.
- It's public. Anyone can call it. It returns two numbers, and the query selects only those two columns.
- Cache Components reaches it too: a
GETwithout request data or queries would be prerendered. This one usesparamsand the database, so it always runs.no-storealso prevents the browser or an intermediary from storing it.
4.2. The component
// app/(public)/events/_components/live-availability.tsx
'use client'
import useSWR from 'swr'
import { fetchJson } from '@/lib/http-client'
import type { Availability } from '@/lib/types'
interface Props {
slug: string
initial: Availability
}
export function LiveAvailability({ slug, initial }: Props) {
const { data, error } = useSWR<Availability>(`/api/events/${slug}/availability`, fetchJson, {
fallbackData: initial,
refreshInterval: 20_000,
})
const { spotsLeft, capacity } = data ?? initial
return (
<div className="mt-4">
<p className="font-medium" aria-live="polite">
{spotsLeft > 0 ? `${spotsLeft} of ${capacity} spots left` : 'Fully booked'}
</p>
{error && (
<p className="text-sm text-slate-600">This figure may be out of date.</p>
)}
</div>
)
}// EventDetails: replaces the spots paragraph
<LiveAvailability
slug={event.slug}
initial={{ spotsLeft: event.spotsLeft, capacity: event.capacity }}
/>This is the pattern that avoids going back to the SPA: the server provides the first value and the browser keeps it up to date.
fallbackDatais available on the first render, including in the HTML. There's no loading state, no jump and no hole for search engines, and without JavaScript the initial value can still be read.- After hydrating, SWR revalidates once. It treats the initial value as stale. It looks wasteful but it isn't: time may have passed between the render and the read, especially if the page was restored during navigation. You can avoid it with
revalidateIfStale: false. refreshIntervalrepeats every 20 seconds. By default SWR doesn't poll while the tab is hidden or offline, and it refreshes when focus returns. In 02-01 you saw that pages are hidden instead of unmounted; when they're hidden their effects are cleaned up, and the polling with them.- If it fails, it keeps the last value and tries again with increasing waits. Replacing a reliable number from a minute ago with an error notice would be worse; a note is enough.
initialis a constructed object, not the whole event (03-03).aria-live="polite"makes a screen reader announce the change without interrupting.
How often should you poll? Do the math: 200 visitors with the event page open every 20 seconds is 10 requests per second, each with its own query. Choose the interval for what it gives the person looking, not for what's possible. If immediacy were needed, the alternative is for the server to notify (Server-Sent Events), which we'll touch on briefly in 07-01.
Try it: open an event page and, with npm run db:studio, change spots_left. Within twenty seconds, or when you return to the tab, the text updates. And don't lose sight of the essential point: this number informs, it doesn't guarantee. What decides whether there's a spot left is the booking transaction, in module 6.
- Suggestions as you type
The search box on /events will suggest titles. First, the data and the endpoint:
// lib/data/events.ts (addition)
export async function suggestEvents(text: string): Promise<Suggestion[]> {
const db = await getDb()
return db
.select({ slug: events.slug, title: events.title })
.from(events)
.where(and(isPublished, ilike(events.title, `%${escapePattern(text)}%`)))
.orderBy(...byDate)
.limit(5)
}// app/api/suggestions/route.ts
import type { NextRequest } from 'next/server'
import { suggestEvents } from '@/lib/data/events'
export async function GET(request: NextRequest) {
const text = request.nextUrl.searchParams.get('q')?.trim().slice(0, 80) ?? ''
if (text.length < 2) return Response.json([])
return Response.json(await suggestEvents(text))
}The minimum and maximum number of characters are checked on the server, even though the client checks them too: the endpoint can be called without going through your form.
On the client, three measures avoid requesting on every key: a delay, a minimum number of characters and a null key, which in SWR means "not yet".
// lib/use-debounce.ts
import 'client-only'
import { useEffect, useState } from 'react'
// Returns the value once it has gone a while without changing
export function useDebounce<T>(value: T, milliseconds: number): T {
const [debounced, setDebounced] = useState(value)
useEffect(() => {
const timer = setTimeout(() => setDebounced(value), milliseconds)
return () => clearTimeout(timer)
}, [value, milliseconds])
return debounced
}// app/(public)/events/_components/search-field.tsx
'use client'
import { useId, useState } from 'react'
import useSWR from 'swr'
import { fetchJson } from '@/lib/http-client'
import type { Suggestion } from '@/lib/types'
import { useDebounce } from '@/lib/use-debounce'
const MIN_LENGTH = 2
export function SearchField({ initial = '' }: { initial?: string }) {
const listId = useId()
const [text, setText] = useState(initial)
const search = useDebounce(text.trim(), 250)
const active = search.length >= MIN_LENGTH
const { data } = useSWR<Suggestion[]>(
active ? `/api/suggestions?q=${encodeURIComponent(search)}` : null,
fetchJson,
{ keepPreviousData: true, revalidateOnFocus: false },
)
const suggestions = active && data ? data : []
return (
<label className="flex flex-col">
Search
<input
name="q"
type="search"
list={listId}
value={text}
onChange={(event) => setText(event.target.value)}
className="border px-2"
/>
<datalist id={listId}>
{suggestions.map(({ slug, title }) => (
<option key={slug} value={title} />
))}
</datalist>
</label>
)
}In FilterForm, the search <label> is replaced with <SearchField initial={filters.q} />. The form is still a Server Component and still submits q, because the field keeps its name. The details:
useDebounceimplements the technique known as debouncing: each keystroke cancels the previous timer, and the request only goes out after a 250 ms pause. React'suseDeferredValueisn't suitable for this: it delays rendering, not requests.- The race is solved. Each text has its own key, and SWR delivers the data for the current key. A late response is stored under its key and isn't shown. As a bonus, when you delete a letter the suggestion is already cached.
keepPreviousDatakeeps the previous suggestions while the new ones arrive, so the list doesn't flicker.revalidateOnFocus: false: suggestions don't need refreshing when you return to the tab.<datalist>is native autocomplete, accessible and with no state to manage. Its appearance is up to the browser; if you needed to control it, you'd use a component from an accessible library rather than writing it by hand.- The field is now controlled (
value), unlike what was done in 02-03. The initial value is updated after filtering because the form container has akeyand is recreated.
If the endpoint fails, there are no suggestions and the form works just the same. It's a progressive enhancement: search never depends on it.
- Infinite scrolling
The third typical case accumulates pages. SWR offers useSWRInfinite, which takes a function that computes each page's key from the previous one; this is where the cursor pagination from 04-02 shines:
import useSWRInfinite from 'swr/infinite'
interface Page {
items: Suggestion[]
cursor: string | null
}
const { data, size, setSize, isLoading } = useSWRInfinite<Page>(
(index: number, previous: Page | null) => {
if (previous && !previous.cursor) return null // No more pages
return previous?.cursor
? `/api/events?cursor=${encodeURIComponent(previous.cursor)}`
: '/api/events'
},
fetchJson,
)data is an array of pages and setSize(size + 1) requests another one. We won't use it in AgendaViva, and it's worth explaining why. With link-based pagination, each page has a URL that can be shared and indexed, the back button works and the footer is reachable. Infinite scrolling suits an endless feed consumed out of inertia; in a guide where people search for something, it gets in the way. If you want a middle ground, a "Load more" button keeps the visitor in control.
- Living alongside the server
When you add a cache in the browser, there are two sources for the same data, and they can contradict each other. A few rules:
- One key, one owner. On the event page, the spots are rendered by
LiveAvailability. The listing's card shows the ones from render time. A few seconds of difference is acceptable; the same event page showing the figure in two places with different values isn't. - The endpoint and the page call the same layer. The query is never duplicated, and the page doesn't call the endpoint (04-01).
- After a mutation, both have to be told. When booking, the Server Action will refresh what's on the server, and the SWR key will have to be invalidated with
mutate. You'll see this in 06-04. - If the initial value is slow, SWR accepts a promise from the server:
<SWRConfig value={{ fallback: { [key]: promise } }}>in a Server Component. Only whoever reads that key suspends. - Form and menu state isn't remote data. Don't put it in the cache.
flowchart LR
P["EventDetails<br/>(server)"] -- "initial" --> C["LiveAvailability<br/>(client)"]
C -- "every 20 s" --> R["route.ts"]
R --> D["lib/data/events"]
P --> D
D --> B[("PostgreSQL")]
7.1. What not to do
| Temptation | Problem | Instead |
|---|---|---|
| Requesting in an effect what the page could already bring | Waterfall, hole and more code | Server Component |
Marking the page with 'use client' to use SWR |
Everything moves to the client | A leaf component with initial data |
| Calling a third-party API with a key from the browser | The key is published | A Route Handler that keeps it |
| Using a Server Action to read | They run one at a time and aren't cached | GET in a Route Handler |
| Polling to find out whether your own action finished | Delay and load | The action's result |
router.refresh() on an interval |
Re-renders the whole route on the server | A small endpoint |
Common Mistakes and Tips
- Not checking
okin the SWR function. A 500 error ends up indata. - An unstable key or a new object for no reason. The cache never hits. A URL is a good key.
- Leaving out
encodeURIComponent. "Rock & Roll" breaks the query. - Polling by default, or with intervals of one or two seconds.
- Showing a loading indicator on every refresh.
isLoadingis only the first time;isValidating, always. - Forgetting that the endpoint is public. Validate, limit and return the minimum.
- Expecting dates in the JSON. They're strings.
- Trusting the browser's data to make decisions. The server checks it when writing.
Exercises
Exercise 1: who asks?
Choose the technique: (1) the list of bookings in "My bookings"; (2) checking whether a slug is available while an event is being created; (3) occupancy figures on a screen placed at the venue entrance; (4) a district selector in a client form; (5) the result of an import that takes a minute.
Solution
- Server Component. It's read once; after canceling a booking, the Server Action refreshes the page.
- Browser, with a delay and a
GET. And again on save, on the server: between the check and the submission, someone else may take it. - Browser, with polling and
refreshWhenHiddenif the screen needs it. The first value comes from the server. - Server, passed as a prop or as a promise with
use. It doesn't change while the form is being filled in. - Browser, with polling of a status endpoint, which stops when it's done. The work is done outside the request (07-04).
Exercise 2: polling sensibly
When the event is fully booked, refreshing every two minutes is enough, and if it has already ended there's no need to refresh at all. refreshInterval accepts a function that receives the latest data. Implement it by passing the component whether the event has ended. Where is that calculated, and why not on the client during render?
Solution
// live-availability.tsx (the new prop is ended: boolean)
const { data, error } = useSWR<Availability>(
ended ? null : `/api/events/${slug}/availability`,
fetchJson,
{
fallbackData: initial,
refreshInterval: (latest) => (latest?.spotsLeft === 0 ? 120_000 : 20_000),
},
)// In an async Server Component, inside a Suspense
await io()
const ended = event.endsAt < new Date()With a null key, SWR doesn't request anything and initial is used. The clock is read on the server, behind io(). Reading it during render on the client risks a hydration error if the event ends between the two renders (03-02), and during prerendering it isn't allowed. A Client Component can also do use(io()) before reading it, but the data doesn't need to be there. It's practice: the course continues with the fixed interval.
Exercise 3: fixing a component
Find the problems and rewrite it with SWR.
'use client'
export function SpotsLeft({ slug }: { slug: string }) {
const [spotsLeft, setSpotsLeft] = useState(0)
useEffect(() => {
setInterval(async () => {
const r = await fetch('/api/events/' + slug + '/availability')
setSpotsLeft((await r.json()).spotsLeft)
}, 1000)
}, [])
return <p>{spotsLeft} spots left</p>
}Solution
- It shows "0 spots left" for the first second: false data, in the HTML too.
- The interval isn't cleaned up: it keeps going after unmount, and in strict mode there are two.
slugisn't in the dependencies: after switching events it asks about the previous one.- Every second, even if the tab is hidden and even if the previous request hasn't come back, with its own race.
- It doesn't check
ok: with a 404,spotsLeftbecomesundefined.
'use client'
export function SpotsLeft({ slug, initial }: { slug: string; initial: Availability }) {
const { data } = useSWR<Availability>(`/api/events/${slug}/availability`, fetchJson, {
fallbackData: initial,
refreshInterval: 20_000,
})
return <p>{(data ?? initial).spotsLeft} spots left</p>
}The key includes the slug, so switching events switches data. If this component and LiveAvailability are on the same page, they share the key and SWR makes a single request.
Conclusion
The browser asks when the data stays alive after the page has rendered or depends on what's being done on it. Even then, the server provides the first value: the client only keeps it up to date. A library like SWR takes care of races, repeated requests, retries and refreshing; a small Route Handler, calling the same data layer, gives it the data. And what's shown informs, but the server is the one that decides.
That wraps up module 4. AgendaViva reads from PostgreSQL and from an external API, with no unnecessary waterfalls, streams each page in parts and personalizes without losing the shell. But it repeats itself too much: the list of venues, which changes once a year, is queried on every visit. Module 5 deals with that. It starts with Static, Dynamic and Partial Rendering, which brings order to everything you've seen about what's generated at build time and what on every request.
