Topic 4 of 39
Server Components
Overview
By default, all components inside the App Router are React Server Components (RSC). They run only on the server, meaning zero JavaScript is sent to the client for them. This leads to faster page loads, smaller bundle sizes, and secure access to backend resources (like databases).
Syntax
tsx
// This component runs ONLY on the server
import db from '@/lib/db';
export default async function UserProfile({ userId }) {
// Direct database query! No API route needed.
const user = await db.user.findById(userId);
return (
<div>
<h1>{user.name}</h1>
<p>Email: {user.email}</p>
</div>
);
}Common Pitfalls
- Trying to use
useStateoruseEffectin a Server Component (it will throw an error). - Passing non-serializable data (like functions) as props from a Server Component to a Client Component.
Interview Questions
Q:
What is the primary benefit of React Server Components?
A:
They reduce the JavaScript bundle size sent to the client, improve performance, and allow direct, secure access to server-side resources (like databases or file systems) without creating intermediate API endpoints.
Real-World Example
Fetching secret API keys securely on the server.
example
tsx
export default async function Dashboard() {
// This API key is never exposed to the browser
const data = await fetch('https://api.secret.com/data', {
headers: { Authorization: `Bearer ${process.env.SECRET_API_KEY}` }
}).then(res => res.json());
return <div>{data.message}</div>;
}Check Your Knowledge
Test your understanding of Server Components with these quick questions.