Course contentsShow
← React
Lesson 1567 of 2,39638. Server Components FundamentalsFree lesson

Direct Database Access in Components

Server Components can query databases directly without API routes, removing the client-server network hop.

Direct Database Access in Components

You'll learn how Server Components can query databases directly inside your React code, eliminating the need for separate API routes.

The Old Way: The API Layer Tax

In traditional React apps, you couldn't call the database from a component. You'd create an API route (like /api/users), call it with fetch() from your component, then parse the response. Every piece of data required this extra network hop, adding latency and boilerplate.

The Server Component Revolution

With Server Components, you can import your database client and query it directly inside the component. Since the component runs on the server, it has full backend access. No API route needed.

// This is a Server Component (default in Next.js app directory)
import { db } from '@/lib/database'

async function UserProfile({ userId }) {
  // Direct database query — no fetch(), no API route
  const user = await db.users.findOne({ id: userId })
  
  return (
    <div>
      <h1>{user.name}</h1>
      <p>{user.email}</p>
    </div>
  )
}

Notice there's no useEffect, no loading state, no fetch() call. The component is async, queries the database with await, and returns JSX. The database call happens once on the server, and only the rendered HTML-like result gets sent to the browser.

Why This Matters

You've collapsed two network requests (browser→API server, API server→database) into one (Next.js server→database). The browser never makes a network call for this data at all. Faster, simpler, fewer files.

Your database credentials stay on the server. Your ORM imports don't bloat the client bundle. Your data fetching logic lives right where you need it.

Key Takeaway: Server Components let you query databases directly in your component code, eliminating API routes and reducing the network hops between user and data.