Server components let you fetch data directly from a database on the server. This keeps your app fast and secure by not sending database code to the browser.
0
0
Server component database queries in NextJS
Introduction
You want to show data from a database on a webpage.
You need to keep database credentials hidden from users.
You want to load data before the page shows to the user.
You want to reduce the amount of JavaScript sent to the browser.
Syntax
NextJS
export default async function Page() { const data = await fetchDataFromDatabase(); return ( <main> {/* Render data here */} </main> ); }
Server components use async functions to wait for data before rendering.
You can import database helpers directly in server components.
Examples
This example fetches a list of users from the database and shows their names in a list.
NextJS
import { getUsers } from '@/lib/db'; export default async function UsersPage() { const users = await getUsers(); return ( <ul> {users.map(user => <li key={user.id}>{user.name}</li>)} </ul> ); }
This example uses Prisma client to get posts from the database and display them.
NextJS
import { db } from '@/lib/prisma'; export default async function PostList() { const posts = await db.post.findMany(); return ( <section> {posts.map(post => ( <article key={post.id}> <h2>{post.title}</h2> <p>{post.content}</p> </article> ))} </section> ); }
Sample Program
This server component fetches all products from the database using Prisma. It then shows each product's name and price in a list.
NextJS
import { db } from '@/lib/prisma'; export default async function ProductList() { const products = await db.product.findMany(); return ( <main> <h1>Products</h1> <ul> {products.map(product => ( <li key={product.id}> {product.name} - ${product.price} </li> ))} </ul> </main> ); }
OutputSuccess
Important Notes
Server components run only on the server, so you can safely use database credentials here.
Do not use client-side hooks like useState or useEffect in server components.
Always await your database calls to ensure data is ready before rendering.
Summary
Server components let you fetch and render database data safely on the server.
Use async functions and await database queries inside server components.
This approach improves security and performance by keeping data fetching server-side.