Server and Client Components: Boundaries, Secrets and Sessions
Move a client-rendered, token-in-localStorage page to a Server Component with an HttpOnly cookie session, keep interactivity in small Client Components, and authorise next to the data.
Contentsand lesson path
On this page
- The brief
- Step 1: Read the session on the server
- Step 2: Push the boundary down
- Step 3: Keep secrets and data access server-only
- Step 4: Authorise next to the data
- Check your understanding
- Apply it
- Review prompt
Lessons of Server Components & Rendering Modes
- Rendering Strategies Side by Side: CSR, SSR, SSG and Streaming Concept · 25 min
- Server and Client Components: Boundaries, Secrets and Sessions Worked example · 30 min
- Fetching, Streaming and Caching Server Data Worked example · 30 min
- Server Actions, Revalidation and Hydration Pitfalls Worked example · 25 min
- Lab: Move a Signed-In Dashboard to the Server Lab · 30 min
- Check: Pick the Rendering Mode Knowledge check · 10 questions
What you will learn
- Split a page into Server and Client Components, placing the use client boundary as low as possible and keeping secrets and server-only code out of the client bundle.
- Add sign-in through an identity provider or auth library (OAuth 2.0 / OpenID Connect), keep the session in a secure HttpOnly cookie rather than browser storage, and enforce authorization in Server Components, Server Actions and Route Handlers instead of only hiding UI.
Prerequisites: Next.js App Router & Routing
01. The brief
A portfolio page of the shop app was first written the way many React apps start: one client component that renders everything. After sign-in the app stashes the access token in localStorage, and the page fetches the portfolio from the browser before it can show anything.
This works, and it hides two costs well. Every byte of the page's logic — including the code that talks to private data — ships to the browser, where any script and any user can read it. And the session token sits in storage that JavaScript can read, so one compromised dependency can steal it. The brief: keep the page, move the rendering and the data work to the server, keep the session out of scripts, and leave the small interactive bits in the browser.
'use client';
import { useEffect, useState } from 'react';
export default function Account() {
const [portfolio, setPortfolio] = useState<Portfolio | null>(null);
useEffect(() => {
const token = localStorage.getItem('access_token') ?? '';
fetch('/api/portfolio', { headers: { Authorization: `Bearer ${token}` } })
.then((r) => (r.ok ? r.json() : Promise.reject(r.status)))
.then(setPortfolio)
.catch(() => setPortfolio(null));
}, []);
if (!portfolio) return <p role="status">Loading your portfolio…</p>;
return (
<main>
<h1>Portfolio for {portfolio.user}</h1>
<p>Total value: {portfolio.total}</p>
</main>
);
}02. Step 1: Read the session on the server
The App Router makes every page a Server Component unless it opts out with 'use client'. A Server Component runs only on the server: it can be an async function, it can read request data such as cookies, and nothing it imports reaches the browser. So the session moves from localStorage to a cookie that JavaScript cannot read, and the page reads it directly.
A small sign-in route handler sets that cookie. What the cookie holds matters as much as how it is stored. Any HTTP client can send any cookie value, so a cookie that simply says amara could be edited to name someone else. The shop app therefore puts only a long random session id in the cookie and keeps a server-side table that maps each id to a user; an id the server never issued matches nothing and counts as signed out.
The attributes then limit where the cookie goes. HttpOnly means the browser stores the cookie and sends it with requests to this site, but page scripts cannot read it, so code injected through a cross-site scripting (XSS) bug cannot steal it. SameSite=lax keeps it off form posts that start on another site, and Secure restricts it to HTTPS, with an exception that browsers and curl make for http://localhost. In a real application the sign-in step itself is delegated to an identity provider through OpenID Connect, usually via a library; the lab lesson shows where that replaces this demo route. Sessions can also be stateless, with the user data signed or encrypted by a server secret, as the Next.js authentication guide describes; they need no table, but you cannot revoke one before it expires without adding a deny list.
import { NextResponse } from 'next/server';
import {
createSession, SESSION_COOKIE, SESSION_MAX_AGE,
} from '../../../lib/session';
export async function POST(request: Request) {
const body = (await request.json().catch(() => null)) as { user?: string } | null;
const user = typeof body?.user === 'string' ? body.user.trim() : '';
const id = createSession(user); // a random id, stored in the server table
if (!id) {
return NextResponse.json({ error: 'unknown user' }, { status: 401 });
}
const response = NextResponse.json({ user }, { status: 201 });
response.cookies.set(SESSION_COOKIE, id, {
httpOnly: true, // page scripts cannot read it
secure: true, // HTTPS only, except on localhost
sameSite: 'lax', // not sent on cross-site POSTs
path: '/',
maxAge: SESSION_MAX_AGE, // seconds
});
return response;
}import { getPortfolio } from '../../lib/data';
import { getSession } from '../../lib/session';
export default async function DashboardPage() {
const session = await getSession(); // reads the HttpOnly cookie
if (!session) {
return (
<main>
<h1>Dashboard</h1>
<p>Please sign in to view your portfolio.</p>
</main>
);
}
const portfolio = await getPortfolio(session.user);
return (
<main>
<h1>Portfolio for {session.user}</h1>
<p>Total value: {portfolio.total}</p>
</main>
);
}Compare the two versions. The old one rendered nothing until the browser finished a network round trip; the new one fetches on the server, close to the data, and sends finished HTML. The old one needed a public /api/portfolio endpoint guarded only by a token the browser holds; the new one calls the data layer directly, where the session is already known.
03. Step 2: Push the boundary down
Interactivity did not disappear: the page still has a note form that shows a pending state while it saves. That form is a Client Component — but a small one. 'use client' marks a file: everything in it, and everything it imports, becomes browser code. Place the directive on the leaf that genuinely needs the browser, and the rest of the tree stays on the server. The component tree, props and composition patterns come from From mockup to component tree; here they gain a second axis — which environment each component runs in.
Props crossing the boundary must be serialisable, because the server has to ship them to the browser: plain objects, arrays, strings, numbers. A database client, a class with methods or a function cannot cross. The data flow has two directions — server renders the tree and passes plain data down; client components send events and mutations back up through Server Actions, which lesson 4 covers.
'use client';
import { useActionState } from 'react';
import { saveNote } from './actions';
export default function NoteForm() {
const [state, formAction, pending] = useActionState(saveNote, { status: 'idle' });
return (
<form action={formAction}>
<label htmlFor="title">Note title</label>
<input id="title" name="title" maxLength={100} required />
<button type="submit" disabled={pending}>
{pending ? 'Saving…' : 'Save note'}
</button>
<p role="status">{state.status === 'error' ? state.message : ''}</p>
</form>
);
}# the lab app on port 3100, amara.txt from its sign-in step
# collect the page's script files and search them for server data
for u in $(curl -s -b amara.txt http://localhost:3100/dashboard \
| grep -o '<script src="[^"]*"' | cut -d'"' -f2); do
curl -s "http://localhost:3100$u"
done | grep -o '12,480' | wc -l
# the same marker in the server-rendered HTML:
curl -s -b amara.txt http://localhost:3100/dashboard | grep -o '12,480' | wc -l0
2Run it against the lab app from the last lesson of this skill, after its sign-in step has saved amara's cookie in amara.txt. The portfolio value appears twice in the HTML the server sent, once in the rendered paragraph and once in the RSC payload that Next inlines in a script tag for hydration, and zero times in any JavaScript file the browser downloads: the data layer, its queries and the session logic never ship. The framework and the form's interactivity do ship, which is exactly the deal the boundary offers.
04. Step 3: Keep secrets and data access server-only
The data layer now holds everything sensitive: database clients, API keys, the mapping from session to rows a user may read. One accidental import from a 'use client' file would copy all of it into the bundle. The server-only package turns that mistake into a build error instead: import it at the top of the module, and any import chain that reaches a client component fails the build. Client-side fetching patterns and their pitfalls were the subject of Fetching data safely; the move to Server Components replaces most of those effects with a direct call.
import 'server-only';
export async function getPortfolio(user: string) {
// Uses an API key read from an environment variable on the server.
// With this import, importing the module from a client component
// is a build error, not a silent bundle of secrets.
}Environment variables follow the same rule. process.env.MY_SECRET is only read on the server; variables that must reach the browser are the ones you deliberately name with a NEXT_PUBLIC_ prefix, and that prefix is a promise that the value is public. Never solve a missing client-side variable by adding the prefix to a secret.
05. Step 4: Authorise next to the data
Rendering the dashboard only for the signed-in user is presentation. The same session check must sit in front of every path that can return or change data: each Server Action, each Route Handler, each data-layer function that takes a user. In the lab app, the notes endpoint re-reads the session and answers 401 without one, and it filters by the session user, so the second account on the same route sees only its own rows.
export async function GET() {
const session = await getSession();
if (!session) {
return NextResponse.json({ error: 'sign in first' }, { status: 401 });
}
// Only this user's rows, never the whole table:
return NextResponse.json({ user: session.user, notes: listNotes(session.user) });
}06. Check your understanding
07. Apply it
Take one page of an application you know that renders and fetches in the browser. Draw its component tree, mark every component that genuinely needs browser APIs, state or event handlers, and put the rest on the server. Write down which props would cross the boundary and check they are serialisable. Then list every endpoint or data function the page touches and answer: if someone called it directly with curl and no session, what exactly would stop them? If the answer is "nothing", you have found the next task.
08. Review prompt
Without looking back, name the four things HttpOnly, SameSite, Secure and the path attribute each do for a session cookie. Then explain to a colleague why the session belongs in a cookie rather than localStorage, and why 'use client' on the root layout is usually a mistake.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.