Next.js
Beginner
1 min read
Understanding React Server Components
Example
// Server Component — direct DB access, zero client JS
// app/users/page.tsx
import { prisma } from '@/lib/prisma';
// This import only exists on the server — never shipped to the browser
import 'server-only';
export default async function UsersPage() {
// Direct database query — no API route needed
const users = await prisma.user.findMany({
select: { id: true, name: true, email: true, createdAt: true },
orderBy: { createdAt: 'desc' },
take: 20,
});
return (
<div>
<h1>Users ({users.length})</h1>
<table className="w-full text-sm">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Joined</th>
</tr>
</thead>
<tbody>
{users.map((user) => (
<tr key={user.id}>
<td>{user.name}</td>
<td>{user.email}</td>
<td>{user.createdAt.toLocaleDateString()}</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
// To prevent accidental client-side imports of server-only modules:
// Install the 'server-only' package and import it at the top of any
// file that must not be bundled for the client.
// npm install server-only