In Next.js, Server Components can fetch data directly from a database. Why is this approach preferred over fetching data via client-side API calls?
Think about where the code runs and what information should stay secret.
Server Components run on the server, so they can safely connect to databases without exposing sensitive credentials to users. Client-side code runs in browsers and should never have direct database access.
Consider a Next.js Client Component that attempts to import a database client and query data directly. What will happen when this component runs in the browser?
Remember where client components run and what environment they have.
Client Components run in the browser, which cannot run Node.js database clients. Attempting to do so causes runtime errors.
Given the following Next.js Server Component code that fetches user names from a database, what will be rendered?
import { db } from '@/lib/db'; export default async function UserList() { const users = await db.user.findMany({ select: { name: true } }); return ( <ul> {users.map(user => <li key={user.name}>{user.name}</li>)} </ul> ); }
Assume the database has users named Alice, Bob, and Carol.
The Server Component fetches user names from the database and renders them as list items. Since the database returns these users, the list shows their names.
Next.js Server Actions allow server-side functions to be called from client components. Which code snippet correctly defines a Server Action to update a user's name in the database?
Server Actions must be async functions that perform server-side logic directly.
Option D correctly defines an async function that updates the database directly. Option D is valid syntax but does not mark the function as a Server Action explicitly. Option D calls an API instead of direct DB access. Option D is missing async and await, causing potential issues.
Examine the following Next.js Server Component code. It throws an error when trying to fetch data. What is the most likely cause?
import { db } from '@/lib/db'; export default async function ProductList() { const products = await db.product.findMany(); return ( <ul> {products.map(p => <li key={p.id}>{p.name}</li>)} </ul> ); }
Consider how async database calls work in JavaScript functions.
The database call returns a Promise. Without marking the component async and awaiting the Promise, products is a Promise object, so calling map on it causes an error.