A Server Component and a Client Component live side by side in the same tree, but they run on different machines. Between them there's a network. Everything that goes from one to the other has to be writable into the RSC Payload and readable on the other side.
This lesson studies that boundary. You'll learn which props can be passed and which can't, why a client component can contain server children, how to hand over a promise instead of a value and how to send only what's needed. These are the answers left pending in 02-02, 02-04 and 02-05, and with them you'll improve the venues page. By the end you'll have a criterion for deciding where to put the directive.
- Two things cross, along different paths
The documentation sums up the boundary in two rules worth memorizing:
- Code crosses through
importstatements. Whatever a client module imports goes into the browser's JavaScript. - Data crosses through props. It must be serializable.
| Question | What to look at |
|---|---|
| Does this code reach the browser? | The import tree |
| Does this data reach the browser? | The props of the Client Components a Server Component renders |
| Is this component a server or a client component? | Who imports it, not who contains it on screen |
The path is one-way. The server can import a client module, and it gets a reference. The client can't import a Server Component: if it imports the file, it turns it into client code.
flowchart LR
subgraph S["Server"]
A["EventDetailPage"] --> B["EventDetails"]
end
subgraph C["Browser"]
D["FavoriteButton"] --> E["lib/favorites"]
end
B -- "import: reference" --> D
B -- "props: eventId, title" --> D
- What can be serialized
React supports a lot more than JSON. This is the list of what a Client Component's prop can be when the one passing it is a Server Component:
| Value | Allowed? | Notes |
|---|---|---|
string, number, bigint, boolean, null, undefined |
Yes | |
Date |
Yes | Arrives as a Date |
Array, Map, Set |
Yes | If their contents are serializable |
ArrayBuffer and typed arrays |
Yes | A Node Buffer isn't: convert it to a Uint8Array |
| Plain object | Yes | One created with { … }, with serializable values |
| JSX (server or client) | Yes | It's the foundation of composition |
| Promise | Yes | If its value is serializable; it's read with use |
| Server Action | Yes | Crosses as a reference (06-01) |
Symbol from Symbol.for |
Yes | Other symbols aren't |
| Regular function | No | Neither handlers, nor callbacks, nor unrendered server components |
| Class and instance of your own class | No | The methods would be lost |
URL, RegExp, connections, ORM objects with methods |
No | They aren't plain objects |
| Object with a null prototype | No |
In 01-04 we decided that startsAt and endsAt would be Date objects, and here you can see why they don't need converting: a Client Component receives them as dates. With a JSON API they'd arrive as text and you'd have to rebuild them.
The restriction only exists at the boundary. Between two Server Components you can pass whatever you like, such as Pagination's createHref function; and between two Client Components too.
2.1. Why not a function
A function is code plus the variables around it. createHref={(pageNumber) => createEventsUrl({ ...filters, page: pageNumber })} captures filters and uses a server module. There's no way to write that into a message. If Pagination had 'use client', you'd get:
Functions cannot be passed directly to Client Components unless you explicitly expose it by marking it with "use server". Or maybe you meant to call this function rather than return it.
The message suggests "use server", but that isn't the way out here: it would turn a local calculation into a request to the server. The real alternatives depend on what the function was for:
| The function was used to… | Instead, pass… |
|---|---|
| Calculate a value per item | The already-calculated result: links={[…]} |
| Render something custom | The JSX: icon={<Icon />} instead of icon={Icon} |
| Format | The formatted text, or a shared module the client imports |
| Respond to an event | Define it inside the Client Component |
| Modify data | A Server Action (module 6) |
The Next.js TypeScript plugin flags function-typed props in client modules in the editor. By convention it accepts the ones named action or ending in Action, because it assumes they're Server Actions. It's a help, not a guarantee: types don't distinguish a regular function from a Server Action.
- Sending only what's needed
A prop that crosses is serialized in full, whether the component uses it or not, and anyone can read it in the page source. That raises two problems: weight and privacy.
Imagine a button that greets the organizer:
// Server Component: sends name, email and role
<OrganizerGreeting user={user} />
// Better: sends the name
<OrganizerGreeting name={user.name} />In the first case the email travels in the RSC Payload even though it doesn't appear on screen. It isn't a React bug; it's what you asked it to do. And there's a trap: narrowing the type doesn't trim the data.
'use client'
type Props = { user: Pick<User, 'name'> }
export function OrganizerGreeting({ user }: Props) {
return <p>Hi, {user.name}</p>
}<OrganizerGreeting user={user} /> compiles, because TypeScript is structural: a full User also has name. At runtime all the fields travel. To trim, you have to build a new object.
The best place is the data layer, where you'll also be able to ask the database for less. For the venues page, which only shows the name and district, define a summary:
// lib/types.ts (addition)
export type VenueSummary = Pick<Venue, 'id' | 'slug' | 'name' | 'district'>// lib/data/venues.ts (addition; also imports VenueSummary)
export async function listVenueSummaries(): Promise<VenueSummary[]> {
const full = await listVenues()
return full.map(({ id, slug, name, district }) => ({ id, slug, name, district }))
}The Pick type describes the shape; the map is what makes it true. When the information is sensitive and not just plentiful, this trimming becomes a security rule, and we'll see it in 08-04.
- Composition: server children in a Client Component
Modal is a client component and shows a quick view that's fetched on the server. ErrorBoundary is a client component and wraps EventResults, which is async. Shouldn't the directive spread?
No, because neither of them imports its children. Remember who writes the JSX:
// EventQuickView: Server Component
<Modal title="Event quick view">
<QuickViewContent params={params} />
</Modal>React distinguishes two roles. An element's owner is the component in whose code it's written; its parent is the one that contains it on screen. EventQuickView is the owner of Modal and of QuickViewContent. Modal is only the parent. Since the owner is a server component, QuickViewContent runs on the server, and Modal receives its output in children, already serialized. It knows where to put it, but not what it is or how it was made.
Modal imports the content |
Modal receives it as children |
|
|---|---|---|
| Where the content runs | Browser | Server |
| Its code reaches the browser | Yes | No |
It can be async and read data |
No | Yes |
Modal can pass it props |
Yes | No: it's already rendered |
The last row is the price. A Client Component can't modify its server children: it doesn't pass them its state or run them again. It only decides whether to show them, where and with what wrapper.
4.1. The slots pattern
There's nothing special about children: any prop can be JSX. With several of them you get slots, named gaps that the server fills:
// components/collapsible.tsx
'use client'
import { useState } from 'react'
interface Props {
header: React.ReactNode
actions?: React.ReactNode
children: React.ReactNode
}
export function Collapsible({ header, actions, children }: Props) {
const [open, setOpen] = useState(false)
return (
<section className="rounded-lg border border-slate-200 p-4">
<header className="flex items-center justify-between gap-4">
<button
type="button"
aria-expanded={open}
onClick={() => setOpen((current) => !current)}
>
{header}
</button>
{actions}
</header>
<div hidden={!open}>{children}</div>
</section>
)
}// In a Server Component
<Collapsible
header={<h3>{venue.name}</h3>}
actions={<Link href={`/venues/${venue.slug}`}>View venue</Link>}
>
<Suspense fallback={<ListSkeleton items={2} />}>
<VenueEvents venueId={venue.id} />
</Suspense>
</Collapsible>The state (open or closed) belongs to the client; the title, the link and the list of events, to the server. It's an example of the pattern and we won't add it: in AgendaViva, <details> is enough.
Notice hidden versus {open && children}. In both cases the content has already been rendered on the server and has traveled. Hiding a server child doesn't avoid its query or protect its information; it's the same warning as with the conditional slots in 02-05.
4.2. Compound components
Some libraries group pieces as properties: Menu.Item, Tabs.Panel. From a Server Component they don't work if they're client components: importing Menu gives you a reference, not the function, and Menu.Item is undefined. React throws Element type is invalid. The fix is to export each piece under its own name (MenuItem), or to use the set inside a Client Component of your own.
The same happens with constants. If a module with 'use client' exports LIMIT = 10 and a Server Component imports it, it doesn't get the number, but a reference it can't use. Values shared by both sides go in a module without the directive, like lib/types.ts or lib/filters.ts.
- Passing promises
On the venues page we'll add a search box that filters as you type. There are few items, already loaded, and the text is transient: by the criterion from 02-02, it's component state and not URL state. That calls for a Client Component with the data.
The direct way is to wait on the server and pass the array:
async function VenueList() {
const venues = await listVenueSummaries()
return <VenueSearch venues={venues} />
}It works, and it's the simplest option. Its limitation is that the entire search box, field included, waits for the data. With a promise you can do something else: start the query on the server, hand over the unresolved promise and have only the list wait for it.
// app/(public)/venues/_components/venue-search.tsx
'use client'
import { Suspense, use, useState } from 'react'
import Link from 'next/link'
import { ListSkeleton } from '@/components/list-skeleton'
import type { VenueSummary } from '@/lib/types'
interface Props {
venues: Promise<VenueSummary[]>
}
export function VenueSearch({ venues }: Props) {
const [text, setText] = useState('')
return (
<>
<label className="mb-6 flex max-w-sm flex-col">
Search venues
<input
type="search"
value={text}
onChange={(event) => setText(event.target.value)}
className="border px-2"
/>
</label>
<Suspense fallback={<ListSkeleton items={3} />}>
<VenueList venues={venues} text={text} />
</Suspense>
</>
)
}
function VenueList({ venues, text }: Props & { text: string }) {
const all = use(venues)
const search = text.trim().toLocaleLowerCase('en')
const visible = all.filter(({ name, district }) =>
`${name} ${district}`.toLocaleLowerCase('en').includes(search),
)
if (visible.length === 0) return <p>No venues match.</p>
return (
<ul className="grid gap-4 sm:grid-cols-3">
{visible.map((venue) => (
<li key={venue.id} className="rounded-lg border border-slate-200 bg-white p-4">
<h2 className="font-semibold">
<Link href={`/venues/${venue.slug}`}>{venue.name}</Link>
</h2>
<p className="text-sm text-slate-600">{venue.district}</p>
</li>
))}
</ul>
)
}// app/(public)/venues/page.tsx
import { ErrorBoundary } from '@/components/error-boundary'
import { listVenueSummaries } from '@/lib/data/venues'
import { VenueSearch } from './_components/venue-search'
export default function VenuesPage() {
const venues = listVenueSummaries() // No await: the promise is handed over
return (
<>
<h1 className="mb-6 text-3xl font-bold">Venues</h1>
<ErrorBoundary title="We can't load the venues">
<VenueSearch venues={venues} />
</ErrorBoundary>
</>
)
}The important parts, step by step:
- The page doesn't wait.
VenuesPageisn'tasync; it starts the query and moves on. The search field stays in the prerendered shell and responds even though the list hasn't arrived. use(venues)reads the promise. If it's pending, it suspendsVenueListand the skeleton is shown; if it's rejected,ErrorBoundarycatches it. Unlike hooks,usecan come after a condition, but it can't go inside atry.- The value arrives in the same response. There's no request from the browser: the server streams the result when it has it.
- The promise is the same on every render, because it comes from a prop. Typing in
textdoesn't change it, sousereturns the value instantly. - The skeleton and
Linkare now client components too here, because this module imports them.ListSkeletonhad no directive and works on both sides.
The fourth point hides the most common mistake. Don't create the promise inside the component that reads it:
// Wrong: a new promise on every render
const data = use(fetch('/api/venues').then((response) => response.json()))Each attempt produces another pending promise and the fallback never goes away; React warns that the promise isn't cached. Promises must come from a Server Component, a cache or a data library (04-06).
await on the server |
Promise and use on the client |
|
|---|---|---|
| Simplicity | Greater | Lesser |
| What waits | The component and everything below it | Only the one that calls use |
| Where the data is rendered | Server or client | Client |
| Use it when | It's the normal case | A Client Component must work right away and the data is slow |
- Where to put the directive
With everything above, these are the possible positions for a page that needs something interactive:
| Position | JavaScript sent | Data sent | When |
|---|---|---|---|
| On the page | The page and everything it imports | Everything it uses, over the network | Almost never; a fully interactive tool |
| On a section | The whole section | The section's | Editor, calendar, instant search |
| On a leaf | The leaf | Two or three values | Buttons, active links, counters |
| On a wrapper with slots | The wrapper | The already-rendered JSX | Modals, collapsibles, providers |
The order of preference runs from the bottom up: first, no directive; then, a wrapper with slots or a leaf; then, a section. To decide:
flowchart TD
A["Is there state, events, effects or browser APIs?"] -- No --> B["Server Component"]
A -- Yes --> C{"Does it wrap content<br/>that doesn't interact?"}
C -- Yes --> D["Client wrapper<br/>with children or slots"]
C -- No --> E{"Does it need data<br/>from the server?"}
E -- No --> F["Client leaf"]
E -- Yes --> G["Client leaf or section<br/>with minimal props or a promise"]
Mark the boundary in your project organization too: a file with 'use client' is a contract with the server. Its props are what will be sent over the network, so write them with the same care as an API response.
Common Mistakes and Tips
- Importing a Server Component from a client one. It becomes a client component. If it's
async, React warns:Only Server Components can be async at the moment. Pass it aschildren. - Passing a component instead of an element:
icon={Icon}with a Server Component is a function. Writeicon={<Icon />}. - Passing the whole entity because it's convenient. It's heavy, and it exposes what isn't shown.
- Relying on
Pickto trim. Types don't exist at runtime. - Converting dates to text before passing them. It isn't needed and loses the type.
- Passing instances: a
URL, a domain class or an ORM object with methods. Pass its text or a plain object. - Marking a function with
'use server'to silence the error. You'd be creating a public entry point to your server (08-06). - Hiding server content on the client in the belief that it isn't sent.
Exercises
Exercise 1: what crosses
A Server Component passes all these props to a Client Component. Say which ones are valid and propose an alternative for the rest: (a) startsAt={event.startsAt}; (b) onClose={() => {}}; (c) districts={new Set(['Downtown', 'Northside'])}; (d) destination={new URL('https://example.com')}; (e) footer={<Footer />}; (f) event={getEventBySlug(slug)}; (g) categories={CATEGORY_LABELS}; (h) format={formatDateTime}.
Solution
- (a) Valid:
Date. - (b) No: a function. Define it inside the Client Component.
- (c) Valid: a
Setof strings. - (d) No:
URLis a class instance. Passdestination="https://example.com". - (e) Valid: it's JSX.
Footerruns on the server. - (f) Valid: it's a promise with a serializable value. The client reads it with
use, inside a<Suspense>, but the whole event would travel. - (g) Valid: a plain object of strings. The client can also import it, because
lib/format.tshas no directive. - (h) No: a function. Pass the already-formatted text or import the module from the client.
Exercise 2: tabs with slots
Create a Tabs Client Component that receives a list of tabs with id, title and content, and shows the selected one. The contents must be able to be async Server Components. Write a usage example with an event's description and its venue details. How many queries are made if the visitor never opens the second tab?
Solution
'use client'
import { useState } from 'react'
interface Tab {
id: string
title: string
content: React.ReactNode
}
export function Tabs({ tabs }: { tabs: Tab[] }) {
const [active, setActive] = useState(tabs[0]?.id)
return (
<>
<div className="flex gap-4">
{tabs.map(({ id, title }) => (
<button
key={id}
type="button"
aria-pressed={id === active}
onClick={() => setActive(id)}
>
{title}
</button>
))}
</div>
{tabs.map(({ id, content }) => (
<div key={id} hidden={id !== active}>
{content}
</div>
))}
</>
)
}// In EventDetails, which is a server component
<Tabs
tabs={[
{ id: 'description', title: 'Description', content: <p>{event.description}</p> },
{
id: 'location',
title: 'Getting there',
content: (
<Suspense fallback={<p>Loading the venue…</p>}>
<EventLocation venueId={event.venueId} />
</Suspense>
),
},
]}
/>The venue query is always made: the content is rendered on the server before anyone knows which tab will be viewed. If it were expensive and rarely visited, it would be better for each tab to be a route or a search param, so that it's only requested when opened.
Exercise 3: fixing a boundary
This code throws an error and, once that's fixed, would still send too much. Fix it.
// Server Component
export async function DashboardTable() {
const events = await listDashboardEvents(PLACEHOLDER_ORGANIZER_ID)
return (
<SortableTable
events={events}
onFormat={(event: AgendaEvent) => formatDateTime(event.startsAt)}
/>
)
}Solution
// Server Component
export async function DashboardTable() {
const events = await listDashboardEvents(PLACEHOLDER_ORGANIZER_ID)
const rows = events.map(({ id, title, startsAt, spotsLeft }) => ({
id,
title,
startsAt,
date: formatDateTime(startsAt),
spotsLeft,
}))
return <SortableTable rows={rows} />
}The function is replaced by its result, date. startsAt is kept too, crossing as a Date, because sorting by the formatted text would give an alphabetical order rather than a chronological one. The descriptions and the other fields no longer travel. The table receives rows designed for it and doesn't depend on the AgendaEvent type.
Conclusion
Code crosses through imports and data through props. Props accept dates, collections, JSX and promises, but not functions or instances, and they're sent in full: trimming is done by building the object, not by narrowing the type. A Client Component can contain server content if it receives it ready-made, and use lets you hand it data that's still on its way.
Slots solve the relationship between a wrapper and its content. What remains is the case where a value matters to many components scattered across the tree, like the color theme or the user. That, along with libraries that don't ship the directive, is the subject of Context, Providers and Third-Party Libraries.
