Next.js › Database Integration with Next.js

Why should database queries always happen on the server rather than in the browser?

Intermediate

Answer

Database credentials and connection strings must remain secret, and browsers cannot be trusted to keep secrets safe since anyone can view the JavaScript running on their machine. Running queries only on the server, inside server components, route handlers, or server actions, keeps these credentials completely hidden from users.
// Safe: runs only on the server
export default async function Page() {
  const users = await db.user.findMany();
  return <UserList users={users} />;
}
Real-world example A company discovers that exposing a database connection string in client side code would let anyone inspect their browser and steal database access, reinforcing why all queries must stay server side.

Common follow-ups: What happens if a database credential accidentally gets exposed in client code?;How do environment variables help keep credentials secure?