Course contentsShow
← React
Lesson 1585 of 2,39639. Server Components in PracticeFree lesson

Database Queries in Components

Server components can import and use database clients directly without exposing credentials to the client.

Database Queries in Components

What you'll learn: How to import database clients directly in server components and query your database without exposing credentials to the browser.

The Revolutionary Pattern

In traditional React apps, you couldn't just import a database client and run queries in your components—credentials would leak to the browser, and the database driver wouldn't even work in client JavaScript. You needed a separate API layer.

Server components change this completely. Since they execute only on the server, you can import database clients like Prisma, PostgreSQL drivers, or MongoDB clients directly and write queries right where you need the data.

How It Works in Practice

import { db } from '@/lib/database'; // Your database client

async function ProductList() {
  // This runs on the server only
  const products = await db.product.findMany({
    where: { active: true },
    orderBy: { name: 'asc' }
  });

  return (
    <ul>
      {products.map(product => (
        <li key={product.id}>{product.name}</li>
      ))}
    </ul>
  );
}

The database connection string, credentials, and even the database driver code never reach the browser. It's truly server-only code.

The Security Win

Think of it like a restaurant kitchen: customers (browsers) can see the menu and receive their food, but they never access the kitchen, see the recipes, or touch the stove. Your database credentials stay in the kitchen (server), while users only see the prepared results (HTML).

You can use any Node.js database library without worrying about bundle size or credential exposure—the import statement itself is a server-only operation.

Key Takeaway: Server components let you import database clients and run queries directly in your components because the code executes exclusively on the server, keeping credentials secure and eliminating the need for separate API routes for simple data fetching.