Client-side Data Fetching
App Router is server-first, not server-only.
Client-side fetching is useful when the browser genuinely owns the lifecycle of the data.
Examples:
- rapidly updating dashboards after initial render
- polling/live status
- browser-only APIs
- user-triggered secondary data
- client cache libraries shared across interactive widgets
- data that does not need to participate in initial server rendering
The question is not βis client fetching allowed?β
It is:
Does this data need browser ownership?
Avoid duplicating server ownershipβ
Bad architecture:
Server Component fetches projects
β renders table
Client Component mounts
β fetches same projects again
You now have two owners and two requests.
Prefer one clear model:
initial server-owned read
+ client mutation/live refresh only when needed
or
client-owned remote state
with deliberate loading/cache policy
Basic client fetchβ
'use client'
import { useEffect, useState } from 'react'
export function StatusPanel() {
const [status, setStatus] = useState<Status | null>(null)
const [error, setError] = useState<Error | null>(null)
useEffect(() => {
const controller = new AbortController()
async function load() {
try {
const response = await fetch('/api/status', {
signal: controller.signal,
})
if (!response.ok) {
throw new Error(`Status request failed: ${response.status}`)
}
setStatus(await response.json())
} catch (error) {
if (!controller.signal.aborted) {
setError(error as Error)
}
}
}
load()
return () => controller.abort()
}, [])
if (error) return <p>Unable to load status.</p>
if (!status) return <p>Loadingβ¦</p>
return <StatusView status={status} />
}
This is valid, but a hand-written effect is not automatically the best solution for sophisticated remote state.
Client data librariesβ
Next.js documentation points to community libraries such as SWR for browser fetching.
A client data library can add:
- cache
- request deduplication
- revalidation
- focus revalidation
- polling
- mutation integration
- race handling
Example shape:
'use client'
import useSWR from 'swr'
const fetcher = (url: string) =>
fetch(url).then(async response => {
if (!response.ok) throw new Error('Request failed')
return response.json()
})
export function LiveStatus() {
const { data, error, isLoading } = useSWR('/api/status', fetcher)
if (error) return <p>Failed to load.</p>
if (isLoading) return <p>Loadingβ¦</p>
return <StatusView status={data} />
}
TanStack Query, RTK Query, and similar libraries can also be valid choices when their broader state/mutation model fits the app.
Server cache vs client cacheβ
These are different systems:
SERVER
Next.js data/output caches
React request memoisation
BROWSER
SWR / TanStack Query / RTK Query cache
browser HTTP cache
local component state
Do not assume invalidating one automatically invalidates the others.
Later mutation/caching phases cover coordination in depth.
Initial server data + client live updatesβ
A common pattern:
Server Component
β initial authoritative snapshot
Client island
β live/polling/subscription updates
Example:
export default async function Page() {
const initial = await getSystemStatus()
return <LiveStatus initialStatus={initial} />
}
The client component can then use the initial value while taking ownership of live updates.
Be explicit about which source wins if the client refetches immediately.
Avoid instant duplicate refetchβ
If the server just fetched data and the client library refetches on mount, you may pay twice.
Possible strategies depend on the library:
- seed initial/fallback data
- configure stale time/revalidation policy
- defer live refresh until needed
Do not blindly disable refetching globally. Choose from freshness requirements.
Pollingβ
poll every 5s
is simple but can become expensive at scale.
Estimate:
10,000 active users Γ 12 requests/minute
= 120,000 requests/minute
Ask whether you need:
- slower interval
- visibility-aware polling
- backoff
- SSE/WebSocket
- server push/event architecture
Browser visibilityβ
For background tabs, continuous polling may waste resources.
Many client libraries support focus/visibility-aware refresh behavior.
If implementing manually, understand the Page Visibility API and product expectations.
Race conditionsβ
User changes a filter quickly:
request A: q=react
request B: q=next
If A finishes after B, naive state updates can display stale results.
Use:
- abort signals
- request identity
- a client library with race handling
Do not assume response order equals request order.
Authenticationβ
Browser requests may use cookies automatically for same-origin requests depending on cookie settings.
Never send server secrets to the browser so it can call a private upstream directly.
If the browser needs access to protected application data:
browser
β authenticated app endpoint / Server Function
server
β authorize
upstream/database
The server remains authoritative.
Client data is untrusted tooβ
A client cache containing:
{ canDelete: true }
is not an authorization decision.
Mutations must re-check permissions on the server.
SEO and first-load trade-offβ
If critical public content is fetched only after mount:
HTML shell
β JS
hydrate
β fetch
β render content
That can delay useful content and may be worse for indexing/first-load experience.
Prefer server rendering for content needed in the initial document when possible.
Client fetching does not require a global storeβ
Remote state and global UI state are different concerns.
A query cache can own server-derived browser data without copying every result into Redux/Zustand.
Avoid duplicate caches unless there is a clear synchronization contract.
Offline requirementsβ
If product requirements include offline support, browser persistence, queued mutations, or background sync, the architecture becomes more client-centric.
Treat that as an explicit product capability, not a default reason to fetch everything in the browser.
Common mistakesβ
Fetching server-renderable data only in effectsβ
Adds a client waterfall unnecessarily.
Server fetch + immediate client fetch of the same resourceβ
Duplicate work and ownership.
Polling every second without scale analysisβ
Can overwhelm your backend.
Treating client cache as authorizationβ
Browser state is user-controlled.
Storing query data in multiple client storesβ
Creates synchronization problems.
Debugging checklistβ
- Determine why the browser owns this data.
- Check whether the server already fetched the same resource.
- Inspect duplicate mount/focus refetches.
- Check race cancellation.
- Check polling frequency and background-tab behavior.
- Verify HTTP status/error handling.
- Measure payload size and request frequency.
- Confirm secrets stay on the server.
- Confirm server mutations re-authorize.
- Test slow network, offline, and tab refocus if relevant.
Interview questionsβ
When is client-side fetching appropriate in App Router?
When the data lifecycle is genuinely browser-owned: live updates, polling, user-triggered secondary data, or client cache behavior that does not need to block initial server rendering.
Why not fetch everything in useEffect?
It adds JavaScript and a browser-side waterfall for data the server could have rendered directly.
How are SWR and the Next.js Data Cache different?
SWR is a browser/client remote-state cache; Next.js server caching operates in the server/framework rendering layer.
Why can server initial data plus client refetch duplicate work?
Because the same resource may be requested once during server render and again immediately after hydration unless the client cache is seeded/configured deliberately.
Exerciseβ
For each feature classify the data owner:
marketing article
live stock ticker
admin table filters
current user permissions
chat presence
checkout totals
Choose:
- server read
- client read
- hybrid initial server + live client
- URL state
- local UI state
Then document loading, error, freshness, security, and duplication risks.