Server and Client Components · Lesson 8 of 24
Next.js Server Components
In the App Router, every component is a Server Component unless you say otherwise. Server Components run only on the server – at build time or when a request arrives. They can be async, talk to databases and private APIs directly, read secret keys, and their code is never sent to the browser. Understanding them is the single most important idea in modern Next.js.
In this lesson
- Where Server Components run – proved with server logs
- Async components and direct data access
- Secrets and environment variables
- What Server Components can't do
Where does the code run?
This page logs a message while rendering. The Suspense + connection() combination makes it render per request, so we can watch it happen:
// app/page.tsx
import { Suspense } from "react";
import { connection } from "next/server";
async function Greeting() {
await connection(); // render on every request
console.log("Rendering <Greeting> on the server"); // where does this appear?
return <p>Hello from the server – Node.js {process.version.split(".")[0]}</p>;
}
export default function Home() {
return (
<main>
<h1>Server Components</h1>
<Suspense fallback={<p>Loading…</p>}>
<Greeting />
</Suspense>
</main>
);
}
Server Components Hello from the server – Node.js v24 server: Rendering <Greeting> on the server
The log line appears in the terminal running Next.js, not in the browser console, and process.version – a Node.js API – works. The browser only receives the rendered result; the component's code isn't in any JavaScript bundle.
Async components and direct data access
Because a Server Component runs on the server, it can read files, query a database or call an internal API without building a separate REST endpoint for it:
// lib/db.ts
import "server-only"; // importing this file from a Client Component fails the build
type Lesson = { id: number; title: string; minutes: number };
const lessons: Lesson[] = [
{ id: 1, title: "What Is Next.js?", minutes: 8 },
{ id: 2, title: "Create a Next.js App", minutes: 10 },
{ id: 3, title: "Routing: Pages and Links", minutes: 9 },
];
export async function getLessons(): Promise<Lesson[]> {
// e.g. await db.select().from(lessonsTable) with Drizzle, or prisma.lesson.findMany()
return lessons;
}
// app/page.tsx
import { getLessons } from "@/lib/db";
export default async function Home() {
const lessons = await getLessons(); // no useEffect, no loading state, no API route
const total = lessons.reduce((sum, l) => sum + l.minutes, 0);
return (
<main>
<h1>Chapter 1</h1>
<ol>{lessons.map((l) => <li key={l.id}>{l.title} ({l.minutes} min)</li>)}</ol>
<p>{total} minutes in total</p>
</main>
);
}
Route (app) ┌ ○ / ○ (Static) prerendered as static content Chapter 1 1. What Is Next.js? (8 min) 2. Create a Next.js App (10 min) 3. Routing: Pages and Links (9 min) 27 minutes in total
Compare that with a client-side React app: there you'd need an API endpoint, a useEffect, loading and error state, and the user would wait for JavaScript before the request even starts. Here the page is fully rendered HTML – and since the data doesn't depend on the request, it was prerendered at build time (○).
Secrets stay on the server
Environment variables are available in Server Components. The JavaScript bundle sent to the browser only includes variables starting with NEXT_PUBLIC_. But be careful – there's a trap. Watch what happens when a Client Component reads a secret:
# .env
PAYMENT_SECRET_KEY=sk_test_51abc
NEXT_PUBLIC_SITE_NAME=LearnFrenzy
// app/client-info.tsx
"use client";
export function ClientInfo() {
return (
<p>
Site: {process.env.NEXT_PUBLIC_SITE_NAME} · key: {process.env.PAYMENT_SECRET_KEY ?? "(not in the browser)"}
</p>
);
}
// app/page.tsx
import { ClientInfo } from "./client-info";
export default function Home() {
return (
<main>
<h1>Checkout</h1>
<ClientInfo />
</main>
);
}
GET / → 200 text/html (HTML page) Response contains "sk_test_51abc": yes Checkout Site: LearnFrenzy · key: (not in the browser) browser pageerror: Minified React error #418; visit https://react.dev/errors/418?args[]=text&args[]= for the full message or use the non-minified dev environment for full errors and additional helpful warnings.
Two things happened:
- In the browser, the key is missing – the bundle doesn't contain it, as promised.
- But the HTML response contains the secret. Client Components are also rendered on the server for the first load, and there
process.envholds every variable. React then noticed that the server HTML and the browser render disagree – the console error #418 is a hydration mismatch.
Never read secrets in a client file
- Use secrets only in Server Components, Server Actions, Route Handlers and modules they import – and pass the result to Client Components as props, never the key.
- Add
import "server-only"at the top of modules that hold secrets or database access, as inlib/db.tsabove. If a Client Component ever imports that module, the build fails instead of exposing it. - Only give the
NEXT_PUBLIC_prefix to values that are truly public (a site name, an analytics ID).
What Server Components can't do
| Server Components can | Server Components can't |
|---|---|
be async and await data | use state or effects (useState, useEffect) |
| access databases, files, secrets | attach event handlers (onClick, onChange) |
| keep large libraries out of the bundle (a Markdown parser, a date library) | use browser APIs (window, localStorage) |
| render Client Components | use React context directly |
For anything interactive, you add a Client Component – the next lesson.
Practice
Try it yourself
Make a Server Component that reads
package.json-style data from a module and shows "Built with Next.js" plus the count of dependencies (use a constant object as the data).Show solution
// lib/project.ts import "server-only"; export async function getProject() { return { name: "my-next-app", dependencies: { next: "16", react: "19", "react-dom": "19" } }; }// app/page.tsx import { getProject } from "@/lib/project"; export default async function Home() { const project = await getProject(); return ( <p> Built with Next.js – {project.name} has {Object.keys(project.dependencies).length} dependencies </p> ); }Built with Next.js – my-next-app has 3 dependencies
Quick check
Are components in app/ Server or Client Components by default?
Server Components.
Where does console.log in a Server Component appear?
In the server's terminal/logs, not the browser console.
Which environment variables reach Client Components?
Only those prefixed with NEXT_PUBLIC_.
Summary
- Components in app/ are Server Components: they run on the server and send no JavaScript.
- They can be async and read databases, files and secrets directly.
- They can't use state, effects, event handlers or browser APIs – that's what Client Components are for.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.