Next.js Zero to Advanced #3: Server Components & Client Components
In Part 2 DigiStore gained a product list, a dynamic detail page, layouts, and 404 and loading screens. But everything is still "static": nothing can be clicked except links. In Part 3 we learn the most important concept in the App Router: Server Components and Client Components. We will build a favorite button, an "Add to Cart" button and a "Read more" component, then split the UI into Header and ProductCard components in a components/ folder.
Server Components: The App Router Default
Every component starts as a Server Component
Every component in the app/ folder (and every component it imports) is a Server Component by default. That means it runs on the server, its output is sent to the browser as HTML plus a compact data format (called the RSC Payload), and the component's JavaScript code is not sent to the browser.
The benefits:
- Direct data access: Server Components can be
asyncand can read a database or files. That is whyProductsPagein Part 2 could simplyawait getProducts(). - Secrets stay safe: API keys or database connections are used on the server and never reach the browser.
- Less JavaScript: the browser downloads less code, so pages appear faster.
Prove it: where does the code run?
Temporarily add one line at the start of the ProductsPage function (app/products/page.tsx):
console.log('ProductsPage rendered on the server')
Open /products. Result: the message appears in the terminal where npm run dev is running, not in the browser console (DevTools). Remove the line after trying it.
Server Component limitations
Because they do not run in the browser, Server Components cannot:
- use state and effects such as
useStateoruseEffect; - attach event handlers such as
onClickoronChange; - access browser APIs such as
window,localStorageordocument.
For those, we need Client Components.
Client Components with "use client"
Our first favorite button
Create a components folder in the project root (next to app and lib), then create components/FavoriteButton.tsx:
// components/FavoriteButton.tsx
'use client'
import { useState } from 'react'
type FavoriteButtonProps = {
productTitle: string
}
export function FavoriteButton({ productTitle }: FavoriteButtonProps) {
const [isFavorite, setIsFavorite] = useState(false)
return (
<button
type="button"
onClick={() => setIsFavorite((prev) => !prev)}
aria-pressed={isFavorite}
aria-label={
isFavorite
? `Hapus ${productTitle} dari favorit`
: `Tambahkan ${productTitle} ke favorit`
}
className="rounded px-2 py-1 text-xl text-red-600 hover:bg-gray-100"
>
{isFavorite ? 'β₯' : 'β‘'}
</button>
)
}
The important points:
'use client'must be on the very first line of the file, before any imports. This directive marks a boundary: this file and everything it imports go into the browser's JavaScript bundle.useState(false)stores state: whether the product is currently a favorite. Every timesetIsFavoriteis called, React re-renders the button.aria-pressedandaria-labelmake this icon button understandable to screen readers. A button that contains only a symbol must have a text label.type="button"prevents the button from accidentally submitting a form if it ever ends up inside a<form>.- Every component in
components/uses a named export (export function FavoriteButton) and is imported with curly braces:import { FavoriteButton } from '@/components/FavoriteButton'. Only special Next.js files such aspage.tsx,layout.tsxandloading.tsxmust useexport default.
The UI text stays in Indonesian because DigiStore is an Indonesian store.
Client Components are still rendered on the server first
The name "Client Component" is a little misleading. On the first load, a Client Component is also rendered to HTML on the server so the page appears quickly. Once its JavaScript has downloaded, React "brings the HTML to life" by attaching event handlers. This process is called hydration. So the difference is: a Server Component runs only on the server, while a Client Component runs on the server and in the browser.
What happens without "use client"?
Try removing the 'use client' line and save. Next.js shows an error saying, roughly, that useState only works in a Client Component and that you need to add the "use client" directive. Put the line back.
Splitting the UI into components/
ProductCard (Server Component)
We will reuse the product card in the list, and in Part 4 we make it prettier with a Tailwind grid. Create components/ProductCard.tsx:
// components/ProductCard.tsx
import Link from 'next/link'
import { FavoriteButton } from '@/components/FavoriteButton'
import { categoryLabels, type Product } from '@/lib/products'
type ProductCardProps = {
product: Pick<Product, 'slug' | 'title' | 'price' | 'category'>
}
export function ProductCard({ product }: ProductCardProps) {
return (
<div className="flex items-start justify-between gap-4 rounded border p-4">
<div>
<Link
href={`/products/${product.slug}`}
className="font-semibold hover:underline"
>
{product.title}
</Link>
<p className="text-sm text-gray-600">
{categoryLabels[product.category]} Β· Rp{' '}
{product.price.toLocaleString('id-ID')}
</p>
</div>
<FavoriteButton productTitle={product.title} />
</div>
)
}
ProductCard does not use 'use client', so it stays a Server Component. But it can render FavoriteButton, which is a Client Component. This is the recommended pattern: most of the UI stays on the server, and only small interactive "islands" become Client Components.
The Pick<Product, ...> type means the card only needs four fields. The component's requirements become clearer and it is easier to reuse.
Using ProductCard on the list page
Update app/products/page.tsx:
// app/products/page.tsx
import { ProductCard } from '@/components/ProductCard'
import { getProducts } from '@/lib/products'
export default async function ProductsPage() {
const products = await getProducts()
if (products.length === 0) {
return <p>Belum ada produk yang dijual.</p>
}
return (
<div>
<h1 className="text-2xl font-bold">Semua Produk</h1>
<ul className="mt-4 space-y-3">
{products.map((product) => (
<li key={product.id}>
<ProductCard product={product} />
</li>
))}
</ul>
</div>
)
}
Open /products and click a heart icon. Result: the icon toggles between β‘ and β₯ without a reload. Each card has its own independent state.
Header (Server Component)
Move the header out of the root layout into components/Header.tsx to keep the layout short:
// components/Header.tsx
import Link from 'next/link'
export function Header() {
return (
<header className="border-b">
<nav
aria-label="Navigasi utama"
className="mx-auto flex max-w-5xl items-center gap-6 p-4"
>
<Link href="/" className="text-lg font-bold">
DigiStore
</Link>
<Link href="/products" className="hover:underline">
Produk
</Link>
</nav>
</header>
)
}
Then, in app/layout.tsx, add import { Header } from '@/components/Header' and replace the whole <header>...</header> block with a single line. The Link import in the layout is no longer used, so you can remove it:
// app/layout.tsx (body only)
<body className={`${geistSans.variable} ${geistMono.variable} antialiased`}>
<Header />
<main className="mx-auto max-w-5xl p-4">{children}</main>
<footer className="mx-auto max-w-5xl p-4 text-sm text-gray-500">
DigiStore: proyek belajar Next.js di FullstackNotes
</footer>
</body>
The header only contains links and no state, so it does not need to be a Client Component. Do not add 'use client' "just in case": every Client Component adds JavaScript that the browser has to download.
Passing Data through Props
The Add to Cart button
Create components/AddToCartButton.tsx:
// components/AddToCartButton.tsx
'use client'
import { useState } from 'react'
type AddToCartButtonProps = {
productTitle: string
}
export function AddToCartButton({ productTitle }: AddToCartButtonProps) {
const [quantity, setQuantity] = useState(0)
return (
<div className="mt-6 flex flex-wrap items-center gap-4">
<button
type="button"
onClick={() => setQuantity((current) => current + 1)}
className="rounded bg-blue-600 px-4 py-2 text-white hover:bg-blue-700"
>
Tambah ke Keranjang
</button>
<p aria-live="polite" className="text-sm text-gray-600">
{quantity === 0
? 'Belum ada di keranjang.'
: `${quantity} Γ ${productTitle} di keranjang.`}
</p>
</div>
)
}
aria-live="polite" makes screen readers announce changes to the cart text. This cart is just browser state for practicing interactivity. Real purchases (creating an Order in the database for the logged-in user) come in Part 10, and there the price and the buyer's identity are always determined on the server, never trusted from the browser.
Rules for props from Server to Client
A Server Component passes data to a Client Component through props, like productTitle above. There are two important rules:
- Props must be serializable: strings, numbers, booleans, arrays, plain objects,
Dateand the like. Regular functions cannot be passed from a Server to a Client Component (the exception is Server Actions, which we cover in Part 8). - Props are sent to the browser: all data you pass to a Client Component is included in the page payload and can be seen by anyone through DevTools. Pass only the fields you need. This habit becomes critical once we have user data: never pass a whole object that might contain sensitive fields such as
passwordHash.
That is why AddToCartButton and FavoriteButton only receive productTitle, not the whole product object.
The Composition Pattern: Server Components as children
A "Read more" component
Sometimes we need an interactive wrapper (such as expand/collapse) around content that should still be rendered on the server. The trick: the Client Component receives that content through the children prop. Create components/ReadMore.tsx:
// components/ReadMore.tsx
'use client'
import { useState } from 'react'
export function ReadMore({ children }: { children: React.ReactNode }) {
const [expanded, setExpanded] = useState(false)
return (
<div>
<div className={expanded ? '' : 'max-h-16 overflow-hidden'}>{children}</div>
<button
type="button"
onClick={() => setExpanded((current) => !current)}
aria-expanded={expanded}
className="mt-2 text-sm text-blue-600 hover:underline"
>
{expanded ? 'Tampilkan lebih sedikit' : 'Baca selengkapnya'}
</button>
</div>
)
}
ReadMore neither knows nor cares what its children are. That content is rendered on the server first, then "slotted" into the Client Component as finished output. The server component code is not added to the browser bundle.
Assembling the detail page
Now put everything together in app/products/[slug]/page.tsx:
// app/products/[slug]/page.tsx
import Link from 'next/link'
import { notFound } from 'next/navigation'
import { AddToCartButton } from '@/components/AddToCartButton'
import { FavoriteButton } from '@/components/FavoriteButton'
import { ReadMore } from '@/components/ReadMore'
import { categoryLabels, getProductBySlug, type Category } from '@/lib/products'
const includedItems: Record<Category, string[]> = {
EBOOK: ['File PDF', 'Contoh kode', 'Update gratis'],
SOURCE_CODE: ['Source code lengkap', 'Panduan instalasi', 'Lisensi pemakaian'],
TEMPLATE: ['File template', 'Dokumentasi', 'Aset desain'],
}
export default async function ProductDetailPage({
params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params
const product = await getProductBySlug(slug)
if (!product) {
notFound()
}
return (
<article>
<div className="flex items-start justify-between gap-4">
<div>
<p className="text-sm text-gray-500">{categoryLabels[product.category]}</p>
<h1 className="text-2xl font-bold">{product.title}</h1>
</div>
<FavoriteButton productTitle={product.title} />
</div>
<p className="mt-2 text-xl">Rp {product.price.toLocaleString('id-ID')}</p>
<div className="mt-4">
<ReadMore>
<p className="leading-relaxed">{product.description}</p>
<h2 className="mt-4 font-semibold">Yang Anda dapatkan</h2>
<ul className="list-inside list-disc">
{includedItems[product.category].map((item) => (
<li key={item}>{item}</li>
))}
</ul>
</ReadMore>
</div>
<AddToCartButton productTitle={product.title} />
<Link href="/products" className="mt-6 inline-block text-blue-600 hover:underline">
β Kembali ke daftar produk
</Link>
</article>
)
}
Open any product. Result: the product details with a heart icon at the top right, a truncated description with a "Baca selengkapnya" (Read more) button, and a "Tambah ke Keranjang" (Add to Cart) button that increases the quantity on every click. The page itself is still a Server Component; only three small "islands" are interactive.
Because Cache Components is enabled, Next.js hides the previous page instead of throwing it away immediately when you navigate to another route. So if you go back to a product page you just visited, state such as the cart quantity may still be there. This is intentional behavior.
Keeping Server Code on the Server
The server-only package
A file in lib/ could accidentally be imported by a Client Component. For our temporary data the impact is small, but from Part 6 onwards lib/ will contain the database connection, and in Part 10 session logic with a secret. Code like that must never end up in the browser bundle. We add a safeguard right now by adding one line at the very top of lib/products.ts:
// lib/products.ts
import 'server-only'
// ...the rest of the Part 2 code stays the same
Next.js recognizes the server-only import internally. Installing the package is optional, but recommended so ESLint and your editor do not treat it as a missing dependency:
npm install server-only
Now deliberately import categoryLabels from @/lib/products inside FavoriteButton.tsx. Result: Next.js immediately shows an error explaining that a module marked server-only was imported from a Client Component. Remove that test import again.
Type imports are still safe. import type { Product } from '@/lib/products' in a Client Component is fine, because TypeScript removes type imports entirely and they produce no JavaScript.
Environment variables
Next.js only includes environment variables prefixed with NEXT_PUBLIC_ in the browser bundle. Other variables such as DATABASE_URL (Part 5) or SESSION_SECRET (Part 10) are available only on the server. Never give a secret the NEXT_PUBLIC_ prefix.
When to Use Which?
| Need | Server Component | Client Component |
|---|---|---|
| Read data from a database | Yes | Not directly |
| Use secrets (API keys) | Yes | Never |
useState, useEffect | No | Yes |
onClick, onChange | No | Yes |
window, localStorage | No | Yes |
| Less JavaScript in the browser | Yes | Adds to the bundle |
The practical rule: start with a Server Component, and turn only the smallest piece that truly needs interactivity into a Client Component. DigiStore's current structure:
components/
βββ AddToCartButton.tsx β 'use client'
βββ FavoriteButton.tsx β 'use client'
βββ Header.tsx β Server Component
βββ ProductCard.tsx β Server Component
βββ ReadMore.tsx β 'use client'
Common Mistakes
- Forgetting
'use client'on a component that usesuseStateoronClick. Next.js shows an error. - Putting
'use client'somewhere other than the first line. The directive must come before all imports. - Marking an entire page or layout as a Client Component just because of one button. Split the button into its own component.
- Importing a Server Component into a Client Component. The imported component becomes client code too. Use the
childrenpattern instead. - Passing functions or whole objects as props from a Server to a Client Component. Functions are not serializable, and whole objects can leak fields you did not need to expose.
- Making a Client Component
async. Only Server Components can beasyncfunctions. - Using
windoworlocalStoragedirectly during render in a Client Component. Remember, it is also rendered on the server. Access browser APIs inside event handlers oruseEffect.
Exercises
- Add a "Kurangi" (Decrease) button to
AddToCartButtonthat lowers the quantity but never below 0. Disable the button (disabled) when the quantity is 0. - Create a
ShareButtonClient Component that copies the product page URL to the clipboard withnavigator.clipboard.writeTextwhen clicked, then shows "Link disalin!" (Link copied!). Make surenavigatoris only accessed inside the event handler. - Move
includedItemsintolib/products.tsas agetIncludedItems(category)function. Try calling it directly fromReadMore.tsxand observe theserver-onlyerror. Then fix it: call the function in the page (a Server Component) and pass the result throughchildrenas before.
Summary
- In the App Router every component is a Server Component by default: it runs on the server, can be
async, is safe for data and secrets, and adds no JavaScript to the browser. - A Client Component is marked with
'use client'on its first line and is needed for state, event handlers and browser APIs. It is rendered on the server and then hydrated in the browser. - Server Components can render Client Components; data is passed through serializable props. Pass only the data you need, because props are sent to the browser.
- The children pattern lets server-rendered content be wrapped by a Client Component.
import 'server-only'prevents server code from being imported into the client, and onlyNEXT_PUBLIC_variables reach the browser bundle.- We now have
components/Header.tsx,ProductCard.tsx,FavoriteButton.tsx,AddToCartButton.tsxandReadMore.tsx.
DigiStore is interactive now, but it still looks plain. In Part 4 we make it look good with Tailwind CSS: a responsive product grid, a reusable Button component, images with next/image, fonts with next/font, and tidy rupiah price formatting. See you there!
Related articles
PostgreSQL Zero to Advanced #1: Introduction & Setup
Start the series by understanding what a relational database is, installing PostgreSQL locally, and getting comfortable with psql commands like \l, \c and \dt.
PHP Zero to Advanced #1: Introduction & Setup
Start your PHP journey: what PHP is, how to install PHP 8.2+, run the built-in development server, and write your very first script with echo.
Ruby on Rails Zero to Advanced #1: Ruby Basics
Start the Rails journey with the language underneath it: irb, variables, strings, puts vs p, and symbols explained with runnable examples.