Menu

Server Components

Lesson 1: Server Components

What is a Server Component?

A Server Component is a React component that runs only on the server. Its output is sent to the browser, but its code is not.

In the App Router, every component is a Server Component unless its file (or a file that imports it) starts with 'use client'.

Can a Server Component… Answer
Be async and await data? Yes
Query a database or read files directly? Yes
Use secret API keys safely? Yes
Use useState, useEffect, or event handlers like onClick? No
Use browser APIs like window or localStorage? No
Add to the JavaScript bundle sent to users? No

Example

// app/courses/page.tsx (Server Component by default)
import { db } from '@/lib/db';

export default async function CoursesPage() {
  const courses = await db.course.findMany({
    where: { published: true },
    orderBy: { title: 'asc' },
  });

  return (
    <ul>
      {courses.map((course) => (
        <li key={course.id}>{course.title}</li>
      ))}
    </ul>
  );
}

How it works

  1. The request reaches the server.
  2. Next.js runs CoursesPage, which queries the database directly. No separate API is needed.
  3. React turns the result into a compact format called the RSC payload and into HTML.
  4. The browser receives the list. The database code and the db library never reach it.

Why this matters:

  • Smaller bundles: heavy libraries such as Markdown parsers stay on the server.
  • Security: connection strings and API keys never leave the server.
  • Fewer round trips: data is fetched next to the database, not across the internet from the browser.

Common mistakes

Mistake Error or effect Fix
Using useState in a Server Component "useState only works in Client Components" Move the interactive part into a Client Component
Adding onClick to a Server Component element Error: event handlers cannot be passed Same as above
Calling your own API route from a Server Component Extra network hop Call the data function directly
Adding 'use client' to fix any error Large bundles, lost server benefits Find the small part that needs the browser

Key takeaways

  • Server Components are the default; they fetch data and keep code off the browser.
  • They cannot use state, effects, or browser APIs.

Try it: Turn the LearnHub courses page into an async Server Component that reads courses from a local JSON file with fs/promises.


Nextjs Tutorial

J

Jebasta





Get in Touch For Details