Topic 27 of 47
Server Components Default
Overview
In the Next.js App Router, all components inside the 'app' directory are React Server Components (RSC) by default. This means they are rendered entirely on the server, sending zero JavaScript to the client for that component.
Syntax
tsx
// app/page.tsx
// This is automatically a Server Component.
// No JavaScript from this component is bundled for the browser.
export default async function Page() {
// We can securely access server environments
const dbPassword = process.env.DB_PASSWORD;
// We can fetch data directly
const data = await fetch('https://api.example.com/data').then(res => res.json());
return <div>{data.title}</div>;
}Common Pitfalls
- Server components cannot use React hooks like useState, useEffect, or useContext. Attempting to do so will throw an error.
- Server components cannot accept functions (event handlers like onClick) as props, because functions cannot be serialized over the network to the client.
Real-World Example
A Server Component accessing the file system natively:
example
tsx
// app/notes/page.tsx
import fs from 'fs';
import path from 'path';
// Server Components can use Node.js APIs natively!
export default async function NotesIndex() {
const notesDir = path.join(process.cwd(), 'content');
const files = fs.readdirSync(notesDir);
return (
<ul>
{files.map(file => (
<li key={file}>{file}</li>
))}
</ul>
);
}