In the previous module you wrote pages, layouts, cards and event pages without deciding where they ran. All those components, except the few that start with 'use client', are Server Components: React runs them on the server, sends their result to the browser and forgets about them. That's why they can be async and read data, and that's why they can't have state.
This lesson opens that box. You'll see what happens from the moment a Server Component runs until it shows up on screen, what the RSC Payload contains, how it differs from good old server rendering, what JavaScript the visitor downloads and what limits this model has. With that foundation, the decisions in the next four lessons stop being recipes.
- Where each component runs
The names invite you to think in two halves: some components on the server and others in the browser. The reality is asymmetric:
| Runs on the server | Runs in the browser | |
|---|---|---|
| Server Component | Yes | Never |
| Client Component | Yes, to generate the initial HTML | Yes |
What defines a Server Component is the second column: its code never leaves the server. A Client Component also goes through the server on the first load, because the HTML the visitor receives includes its output. It's called a "client" component because it also runs in the browser.
"On the server" doesn't always mean "on every request" either. A Server Component can run at four different moments:
| Moment | Example in AgendaViva |
|---|---|
| At build time, during prerendering | Header, Footer, the /events heading |
| When serving a full load | UpcomingEvents, which waits for uncached data |
When navigating with Link, for whatever is missing |
EventContent when you click a card |
| When the route is requested again | retry after an error, router.refresh(), a revalidation (05-04) |
Server Components don't tell these cases apart. Their function is called, returns a tree and finishes. When each one is appropriate is the subject of module 5.
1.1. It's not the same as SSR
SSR (server-side rendering) existed long before. With it, React ran the components on the server to produce HTML and also sent their code, which the browser ran again to hydrate that HTML. The same component ran twice, and its code had to work in both places.
| Classic SSR | Server Components | |
|---|---|---|
| What it produces | HTML | RSC Payload, from which HTML is also generated |
| The component's code | Is sent to the browser | Isn't sent |
| Is hydrated | Yes | No |
| Can update without the server | Yes, with its state | No: it has to be rendered again on the server |
| Can use a database or a secret | Only in separate functions, such as getServerSideProps |
Yes, in the component itself |
They're complementary mechanisms, and Next.js uses both: Server Components generate the RSC Payload; then that output and the Client Components are rendered to HTML. Saying that a part is "rendered on the server" describes where its HTML comes from. Saying that it's a "Server Component" describes where its code lives.
- From component to screen: the RSC Payload
The output of Server Components is serialized in a format of React's own, the RSC Payload. According to the documentation, it contains three things:
- The rendered result of the Server Components.
- Placeholders where the Client Components go, with references to their JavaScript files.
- The props a Server Component passes to a Client Component.
Take an event card. EventCard is a server component and contains a Link, which is a client component. Stripped down to the essentials, its fragment looks something like this:
7:I[ …module identifier and files…, "Link" ]
["$","article",null,{"className":"rounded-lg …","children":[
["$","p",null,{"children":"Concert"}],
["$","h3",null,{"children":
["$","$L7",null,{"href":"/events/riverside-quartet","children":"Riverside Quartet"}]}],
["$","p",null,{"children":"Friday, May 12 at 08:30 PM"}],
["$","p",null,{"children":"84 spots left"}]
]}]The format is internal and may change; what matters is what you can see and what you can't:
- There's no trace of
EventCard. Only what it returned is there: anarticlewith its children. The function, and everything it imports (formatDateTime,CATEGORY_LABELS), stayed on the server. - The date is already text. The formatting was applied before sending.
- The
Linkisn't resolved. In its place there's a reference ($L7) to the client module and the props the browser will run it with. - Only what's rendered travels. The event has
capacity,organizerIdanddescription, and none of them appear, because the card doesn't use them and they didn't cross over to a Client Component.
That last point is the practical difference from an API that returns JSON: you send the interface, not the record.
2.1. The first load
sequenceDiagram
participant N as Browser
participant S as Server
N->>S: GET /events
S->>S: Runs the Server Components and generates the RSC Payload
S->>S: Generates HTML from that output and the Client Components
S-->>N: HTML and, in the same document, the RSC Payload
N->>N: Paints the HTML (doesn't respond to clicks yet)
N->>S: Requests the JavaScript for the Client Components
N->>N: Rebuilds the tree from the RSC Payload and hydrates
The document carries the same information twice, and each copy has its job. The HTML lets you see the content without waiting for JavaScript, and it's what search engines read. The RSC Payload lets React know which tree that HTML represents: which parts are fixed and where the Client Components that need hydrating are.
Hydration means running the Client Components in the browser and wiring up their events to the HTML that already exists. Server Components aren't hydrated: there's no function to run and no event to wire up. In the guide, a list of six cards hydrates its links and nothing else.
2.2. Subsequent navigations
Clicking a Link doesn't request a document. The browser asks for the RSC Payload of whatever is missing, React compares it with the current tree and updates the DOM. New Client Components are rendered entirely in the browser, with no prior HTML, and therefore without hydration.
That comparison explains something you've already seen: when you filter the guide, the server returns a new list, and the state of the Client Components that remain (a half-typed field, an open menu) isn't lost. React doesn't replace the HTML; it reconciles trees.
- Async components
A Server Component can be an async function, and await pauses only that component. The ones above it have already finished, and its siblings carry on. Meanwhile, the nearest <Suspense> above shows its fallback.
async function VenueEvents({ venueId }: { venueId: string }) {
const events = await listEventsByVenue(venueId)
if (events.length === 0) return <p>No events scheduled.</p>
return (
<ul className="grid gap-4 sm:grid-cols-2">
{events.map((event) => (
<li key={event.id}>
<EventCard event={event} />
</li>
))}
</ul>
)
}Compare it with what the same block would require in an SPA: an endpoint, an effect, three state variables (data, loading, error), cancellation if venueId changes, and the race between responses. None of that is needed here, for a fundamental reason: the component runs once per render and can't be left halfway with a stale value.
| In an SPA | In a Server Component |
|---|---|
useEffect with fetch |
await on a function from lib/data/ |
loading state |
The <Suspense> of whoever places it |
error state |
The nearest error boundary |
useMemo for an expensive calculation |
A direct calculation: there won't be another render in the browser |
| Canceling the request on unmount | There's no mounting or unmounting |
Three rules worth locking in:
- Only Server Components can be
async. A Client Component reads promises withuse, as you'll see in 03-03. - Conditions go wherever you like.
awaitisn't a hook: it can sit behind anifor inside a loop. That said, anawaiton every iteration chains the waits; how to avoid that is the subject of 04-03. - Don't create an endpoint to call yourself. A Server Component that
fetches a route in its own application adds an HTTP request to reach a function it could have imported.
- What it can't do, and why
All the limitations come from the same thing: the function runs, hands over its output and disappears. Nothing is left in memory that could change or respond.
| It can't use… | Reason | What to do |
|---|---|---|
useState, useReducer |
There's no instance to hold the state | Client Component, or the URL |
useEffect, useLayoutEffect, useRef on the DOM |
There's no DOM and no mounting | Client Component |
onClick, onChange… |
They're functions, and the browser is what has to run them | Client Component, or native elements |
window, document, localStorage |
They don't exist on the server the way they do for the visitor | Client Component |
Context (createContext, useContext) |
It isn't available in Server Components | Client provider (03-04), React.cache |
| Class components | They only work as Client Components | A function, or a Client Component |
| Custom hooks that use any of the above | They inherit the limitation | Client Component |
If you try, the error shows up when the module is compiled. With useState, abridged:
You're importing a module that depends on `useState` into a React Server Component module. This API is only available in Client Components. To fix, mark the file (or its parent) with the "use client" directive.
An event handler on an element, on the other hand, fails at render time, with Event handlers cannot be passed to Client Component props. The message is puzzling because your <button> isn't a Client Component, but it describes the problem: a function can't be written into the RSC Payload.
There's something less obvious: it doesn't update on its own. If an event's spots left change, the event page someone has open keeps showing the old number. To refresh it, you have to render again on the server (a navigation, refresh, a Server Action) or move that figure into a Client Component that fetches it, as you'll do in 04-06.
And one favorable consequence: since its code is private, it can contain queries, business rules or keys. Lesson 03-05 shows how to make sure it stays that way.
- What JavaScript reaches the browser
A component being a server component doesn't leave the page without JavaScript. What it leaves out is its own.
| Sent | Not sent |
|---|---|
| React and the client side of Next.js (navigation, prefetching) | Server Components |
| The route's Client Components | Whatever only Server Components import |
| Everything the Client Components import | lib/data/, the ORM, the templates |
| Formatting, Markdown, syntax highlighting libraries… used on the server |
The savings show up with dependencies. If the event descriptions were in Markdown, the library that converts them could weigh more than all of the page's own code. In a Server Component it costs nothing in the browser: it runs on the server and the already-converted HTML is what travels.
The flip side exists too. A list of thousands of items rendered on the server produces a large HTML document and a large RSC Payload, even without JavaScript. Server Components reduce code, not content: pagination is still necessary.
5.1. Interactivity without your own JavaScript
Before moving a component to the client, ask whether the browser already knows how to do it. <details> opens and closes, <form> submits, <a> navigates, <dialog> and elements with popover show themselves. They all work in a Server Component.
Add a collapsible block with the booking conditions to the event page:
// app/(public)/events/_components/practical-info.tsx
import type { AgendaEvent } from '@/lib/types'
const MINUTE = 60_000
export function PracticalInfo({ event }: { event: AgendaEvent }) {
const duration = (event.endsAt.getTime() - event.startsAt.getTime()) / MINUTE
return (
<details className="mt-6 rounded-lg border border-slate-200 p-4">
<summary className="cursor-pointer font-medium">Practical information</summary>
<ul className="mt-2 list-disc pl-5">
<li>Approximate duration: {duration} minutes.</li>
<li>Capacity: {event.capacity} people.</li>
<li>Free admission with advance booking.</li>
</ul>
</details>
)
}Place it at the end of EventDetails, inside the <article>: <PracticalInfo event={event} />. The duration is calculated on the server and the browser handles the disclosure, even before hydrating. What's more, since with Cache Components pages are hidden instead of unmounted (02-01), if the visitor opens it, goes to another page and comes back, they'll find it still open.
- An X-ray of AgendaViva
With all of the above, you can classify what already exists. Follow the /events tree:
RootLayout server
└── PublicLayout server
├── Header server
│ ├── Link (logo) CLIENT (from Next.js)
│ └── NavLink CLIENT (usePathname)
│ └── Link CLIENT
├── EventsLayout server
│ └── EventsPage server
│ ├── FilterForm server, async
│ │ └── Form CLIENT (from Next.js)
│ └── ErrorBoundary CLIENT (error boundary)
│ └── EventResults server, async
│ └── EventList server, async
│ ├── EventCard server
│ └── Pagination server
└── Footer server- The client components are at the edges, almost always as small leaves. That's the shape you want a tree to have.
ErrorBoundaryis a client component and contains async server components. It isn't a contradiction: the one that writes them in its JSX isEventsPage. Lesson 03-03 explains the rule.FilterFormis an interactive form with no client code of its own. It fetches the districts, renders the fields and delegates submission toForm.Paginationreceives a function as a prop. It can because it's a server component. If one day it got'use client', it would stop working.
The default decision is therefore simple: server until there's a specific reason. The reasons are state, events, effects or browser APIs. "It's a form", "it's repeated a lot" or "it comes from a library" aren't reasons on their own.
- Checking it
Three quick experiments, best done with npm run build and npm run start:
- Where it runs. Put a
console.log('EventCard')in the card and another one inNavLink. When you reload/events, the first one only appears in the terminal. The second appears in the browser console and also on the server, when the server generates the HTML: at build time, if that part was prerendered, or during the request. - The document's RSC Payload. Open "View Page Source" on
/eventsand search for "Riverside Quartet". It appears in the HTML and again inside the<script>tags at the end. - A navigation's RSC Payload. In the network tab, click a card. The requests with
_rscin the address don't return HTML, but the format from section 2.
Remove the console.log calls when you're done.
Common Mistakes and Tips
- Confusing a Server Component with static HTML. It can run on every request; what it doesn't do is run in the browser.
- Thinking Client Components don't appear in the HTML. They're prerendered just the same. A search engine sees them, as long as their content doesn't depend on a user action.
- Adding
'use client'to be able to useasync. It's exactly the opposite: Client Components can't be asynchronous. - Using
useEffectto load data the server already knows. It delays the content and ships code that isn't needed. - Modifying a Server Component's DOM with your own script. React doesn't know about it, and the next update may undo it or break.
- Expecting a Server Component to "react". If the data changes, it has to be rendered again on the server.
- Reading the clock or a random value carelessly. During prerendering it would be frozen for everyone, and with Cache Components Next.js treats it as an error (01-04).
Exercises
Exercise 1: server or client
Decide whether each piece needs to be a Client Component and why: (1) a table with an event's bookings; (2) a button that copies the link to the clipboard; (3) a text that shows "Only a few spots left" if there are fewer than ten; (4) an FAQ accordion; (5) a text field that shows how many characters are left as you type; (6) an interactive map from a library that draws on a <canvas>.
Solution
- Server. It only reads and renders.
- Client. It needs an event and
navigator.clipboard. - Server. It's a condition on a piece of data; it's refreshed whenever the event page is rendered.
- Server, with
<details>. You'd only move it to the client if the design called for something the native element doesn't offer. - Client. The counter changes with every keystroke: that's state.
- Client. It uses the DOM and responds to events. A Server Component can fetch the map's data and pass it in.
Exercise 2: what travels
In this component, which parts reach the browser in the RSC Payload and which don't? Assume BookButton is a Client Component.
import { BookButton } from '@/components/book-button'
import { calculateOccupancy } from '@/lib/occupancy'
export async function EventSummary({ slug }: { slug: string }) {
const event = await getEventBySlug(slug)
if (!event) return null
const occupancy = calculateOccupancy(event)
return (
<section>
<h2>{event.title}</h2>
<p>{occupancy}% full</p>
<BookButton eventId={event.id} spots={event.spotsLeft} />
</section>
)
}Solution
They travel: the <section> with the title and the already-calculated percentage, a reference to the BookButton module and its two props, eventId and spots. Separately, the browser downloads the JavaScript for BookButton.
They don't travel: the code of EventSummary, calculateOccupancy, getEventBySlug and the event's other fields, such as organizerId or status.
If the prop were event={event}, all its fields would be sent even though the button only read two. It's a difference you can't see on screen, and 03-03 covers it in detail.
Exercise 3: back to the server
A teammate has written this component to show the venues. Rewrite it as a Server Component and say what goes away.
'use client'
export function VenueSelect() {
const [venues, setVenues] = useState<Venue[]>([])
const [loading, setLoading] = useState(true)
useEffect(() => {
fetch('/api/venues')
.then((response) => response.json())
.then(setVenues)
.finally(() => setLoading(false))
}, [])
if (loading) return <p>Loading…</p>
return (
<select name="venueId">
{venues.map((venue) => (
<option key={venue.id} value={venue.id}>{venue.name}</option>
))}
</select>
)
}Solution
import { listVenues } from '@/lib/data/venues'
export async function VenueSelect() {
const venues = await listVenues()
return (
<select name="venueId">
{venues.map((venue) => (
<option key={venue.id} value={venue.id}>
{venue.name}
</option>
))}
</select>
)
}
// Whoever uses it decides what's shown while it waits
<Suspense fallback={<p>Loading…</p>}>
<VenueSelect />
</Suspense>The two state variables go away, along with the effect, the /api/venues endpoint and the sending of the fields the dropdown doesn't show (address, capacity, district). The <select> isn't controlled: the browser keeps the selection and the form submits it by its name. What's more, a failed query, which the original ignored, now reaches the error boundary.
Conclusion
A Server Component runs on the server, delivers its output in the RSC Payload and never reaches the browser, either as code or as an instance. That's where its advantages come from (direct data access, secrets kept safe, dependencies that cost the visitor nothing) and its limits (no state, no events, no updating on its own). In AgendaViva almost everything is a server component, and Client Components show up as small pieces at the edges of the tree.
Those pieces are the next step. In Client Components and the use client Directive you'll see exactly what the directive you've been writing without explanation means and how hydration works when something doesn't match, and you'll give the guide its first real interaction: favorites.
