You add a console.log to a component and it shows up in your terminal instead of the browser. You add useState and the build fails. You mark a file with 'use client' and suddenly a database library is being bundled for the browser. If any of that sounds familiar, the problem is usually not the code. It is the mental model of where each piece of it runs.
This article is for React developers working with Server Components, most often through the Next.js App Router. We will build a picture of the two environments, look at how the boundary between them works, and finish with patterns for real pages and the cases where Server Components are not the right tool.
Two environments, one tree
#With Server Components, a single React tree is split across two environments.
- Server Components run only on the server. That can be at build time, when a page is prerendered, or at request time. Their code is never sent to the browser.
- Client Components are the components you already know. They can use state, effects and event handlers, and their code is sent to the browser.
The name "Client Component" is a little misleading. A Client Component also runs on the server during the first render, so the user gets HTML straight away. Then it runs again in the browser to hydrate that HTML and make it interactive. So the more accurate rule is:
- Server Components run on the server only.
- Client Components run on the server for the initial HTML and in the browser from then on.
When a Server Component renders, React does not produce HTML directly. It produces the RSC payload, a serialised description of the tree. Where the tree contains a Client Component, the payload holds a reference to that component's JavaScript file plus the props to pass it. The framework uses the payload to build HTML for the first load, and the browser uses it to reconcile the tree on later navigations.
Server Components are the default
#In the Next.js App Router, every component in the app directory is a Server Component unless you say otherwise. That means you can make it async and fetch data directly.
_17// app/articles/page.tsx_17import { db } from "@/lib/db";_17_17export default async function ArticlesPage() {_17 const articles = await db.article.findMany({_17 where: { published: true },_17 orderBy: { date: "desc" },_17 });_17_17 return (_17 <ul>_17 {articles.map((article) => (_17 <li key={article.id}>{article.title}</li>_17 ))}_17 </ul>_17 );_17}
None of this code reaches the browser. The database client, the query and any secrets it reads stay on the server. The browser only receives the rendered list.
What a Server Component cannot do is anything that needs to exist in the browser after render:
useState,useReduceroruseEffect- event handlers such as
onClickoronChange - browser APIs like
window,localStorageorIntersectionObserver - context providers and consumers created with
createContext
If you try, you get a build error telling you the component needs to be a Client Component.
Marking the boundary with use client
#The 'use client' directive goes at the top of a file, before any imports.
_14// app/articles/like-button.tsx_14"use client";_14_14import { useState } from "react";_14_14export function LikeButton({ initialCount }: { initialCount: number }) {_14 const [count, setCount] = useState(initialCount);_14_14 return (_14 <button onClick={() => setCount((c) => c + 1)}>_14 Like ({count})_14 </button>_14 );_14}
The important detail is that 'use client' marks a boundary in the module graph, not a single component. Everything that file imports, and everything those files import, becomes part of the client bundle. So if a Client Component imports a large date library or a markdown parser, that library now ships to the browser.
This is why the usual advice is to push 'use client' towards the leaves of the tree. Keep the page, the layout and the data fetching in Server Components, and mark only the small interactive parts as Client Components.
_20// app/articles/[id]/page.tsx (Server Component)_20import { getArticle } from "@/lib/articles";_20import { LikeButton } from "./like-button";_20_20export default async function ArticlePage({_20 params,_20}: {_20 params: Promise<{ id: string }>;_20}) {_20 const { id } = await params;_20 const article = await getArticle(id);_20_20 return (_20 <article>_20 <h1>{article.title}</h1>_20 <div dangerouslySetInnerHTML={{ __html: article.html }} />_20 <LikeButton initialCount={article.likes} />_20 </article>_20 );_20}
The article body is rendered on the server and arrives as HTML. Only LikeButton and its tiny dependency tree are sent as JavaScript.
What can cross the boundary
#When a Server Component renders a Client Component, the props are serialised into the RSC payload. That means they must be values React knows how to serialise. The supported types include:
- strings, numbers, booleans,
null,undefinedandbigint - plain objects and arrays made of supported values
Date,Map,Set, typed arrays andArrayBuffer- JSX elements, including other Server Components
- Promises
- Server Functions
What cannot cross is anything that only makes sense in memory on the server: ordinary functions, class instances and symbols that are not registered globally.
_10// This fails: a plain function is not serialisable_10<Filter onChange={(value) => console.log(value)} />_10_10// This fails: a class instance loses its prototype_10<Profile user={new User(row)} />_10_10// This works: pass plain data instead_10<Profile user={{ id: row.id, name: row.name }} />
A good habit is to map database rows to small plain objects before passing them down. It keeps the payload small and stops you accidentally sending columns, such as an email address or a password hash, that the browser should never see. Every prop you pass to a Client Component ends up in the page source.
Server Components inside Client Components
#A Client Component cannot import a Server Component. Once you are inside a client module, everything it imports is client code. But a Client Component can receive a Server Component as a prop, most often as children.
_21// app/components/collapsible.tsx_21"use client";_21_21import { useState, type ReactNode } from "react";_21_21export function Collapsible({_21 title,_21 children,_21}: {_21 title: string;_21 children: ReactNode;_21}) {_21 const [open, setOpen] = useState(false);_21_21 return (_21 <section>_21 <button onClick={() => setOpen(!open)}>{title}</button>_21 {open && children}_21 </section>_21 );_21}
_11// app/page.tsx (Server Component)_11import { Collapsible } from "./components/collapsible";_11import { RecentComments } from "./components/recent-comments";_11_11export default function Page() {_11 return (_11 <Collapsible title="Recent comments">_11 <RecentComments />_11 </Collapsible>_11 );_11}
RecentComments is still a Server Component. It is rendered on the server and its output is slotted into the client wrapper. This pattern is how you keep context providers, tabs, modals and other interactive shells on the client without dragging everything inside them into the bundle.
Streaming data with promises
#Because Promises can be passed as props, a Server Component can start a slow request and hand the unresolved promise to a Client Component. The client reads it with use, and a Suspense boundary shows a fallback until it resolves.
_14// app/dashboard/page.tsx (Server Component)_14import { Suspense } from "react";_14import { getStats } from "@/lib/stats";_14import { StatsChart } from "./stats-chart";_14_14export default function Dashboard() {_14 const statsPromise = getStats(); // not awaited_14_14 return (_14 <Suspense fallback={<p>Loading stats…</p>}>_14 <StatsChart statsPromise={statsPromise} />_14 </Suspense>_14 );_14}
_10// app/dashboard/stats-chart.tsx_10"use client";_10_10import { use } from "react";_10import type { Stats } from "@/lib/stats";_10_10export function StatsChart({ statsPromise }: { statsPromise: Promise<Stats> }) {_10 const stats = use(statsPromise);_10 return <pre>{JSON.stringify(stats, null, 2)}</pre>;_10}
The rest of the page is sent immediately, and the chart streams in when the data arrives.
use server is not the opposite of use client
#This trips up a lot of people. There is no 'use server' directive for Server Components. Server Components need no directive at all, because they are the default.
'use server' marks Server Functions: async functions that run on the server but can be called from the client, for example from a form action or an event handler.
_11// app/articles/actions.ts_11"use server";_11_11import { db } from "@/lib/db";_11_11export async function likeArticle(id: string) {_11 await db.article.update({_11 where: { id },_11 data: { likes: { increment: 1 } },_11 });_11}
A Client Component can import likeArticle and call it. React turns the call into a network request. Treat every Server Function like a public API endpoint: check who is calling it and validate its arguments, because anyone can send that request.
Keeping server code on the server
#It is easy to import a server-only module into a Client Component by accident, especially through a shared utility file. Two things help.
First, the server-only package. Import it at the top of any module that must never reach the browser, and the build fails if a client module imports it.
_10// lib/db.ts_10import "server-only";_10_10export const db = createDatabaseClient(process.env.DATABASE_URL);
Second, environment variables. Next.js only inlines variables prefixed with NEXT_PUBLIC_ into client code. Anything else is undefined in the browser, which protects secrets but can also confuse you if a Client Component reads a variable that works fine on the server.
A quick reference
#| Question | Server Component | Client Component |
|---|---|---|
| Runs at build or request time on the server | Yes | Yes, for initial HTML |
| Runs in the browser | No | Yes |
| Code sent to the browser | No | Yes |
| Can be async and await data | Yes | No, use use with a promise |
| State, effects, event handlers | No | Yes |
| Can read secrets and the database | Yes | No |
| Where console.log appears | Terminal | Browser console (and terminal during SSR) |
In development, React also replays Server Component logs in the browser console, labelled as coming from the server, which helps when you are not watching the terminal.
Version support
#Server Components have been stable since React 19.0, and the current release line is React 19.3. They need a framework or bundler integration to work, because something has to split the module graph and serve the RSC payload. The Next.js App Router is the most widely used option and is where most of these examples come from. Other frameworks have their own integrations at different levels of maturity, so check your framework's documentation before relying on them.
Keep react, react-dom and your framework on their latest patch releases. Server Components and Server Functions accept requests from the network, and security fixes for that machinery have shipped as patch releases.
When not to use it
#Server Components are a good default for content-heavy pages, but they are not free.
- Highly interactive apps. A drawing tool, a spreadsheet or a dashboard where nearly everything responds to input will end up mostly client code anyway. The extra boundary adds complexity without saving much JavaScript.
- Apps with no server. If you deploy static files to a CDN and talk to a separate API, a client-rendered app or a static site generator may be simpler.
- Widgets embedded in other sites. A component you drop into someone else's page has no React server behind it.
- Teams new to React. The two-environment model is one more thing to learn. If your app is small, a plain client-side React app is fine.
Wrapping up
#- Server Components run only on the server and send no JavaScript. Client Components render on the server first, then run in the browser.
'use client'marks a boundary in the module graph. Everything a client file imports ships to the browser, so keep the directive near the leaves.- Props crossing the boundary must be serialisable. Pass plain data, and remember it all ends up in the page source.
- Pass Server Components to Client Components as
childrenrather than importing them. 'use server'is for Server Functions, which are public endpoints. Validate and authorise every call.
Test yourself
Testing yourself is one of the best ways to make what you read stick. Turn over each card and answer the 5 questions to see how much you remember.
quick question
Was this article helpful?
by Danny