Bird
Raised Fist0
NextJSframework~20 mins

Why database access matters in NextJS - Challenge Your Understanding

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Database Access Mastery in Next.js
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
2:00remaining
Why do Next.js Server Components prefer direct database access?

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?

ABecause client-side API calls are faster and more secure than server-side database access.
BBecause Server Components cannot fetch data from APIs, only databases.
CBecause Server Components run on the server, they can securely access the database without exposing credentials to the client.
DBecause direct database access on the client improves SEO and performance.
Attempts:
2 left
💡 Hint

Think about where the code runs and what information should stay secret.

component_behavior
intermediate
2:00remaining
What happens if a Next.js Client Component tries to access the database directly?

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?

AIt will successfully fetch data because the browser can connect to databases directly.
BIt will throw a runtime error because database clients cannot run in the browser environment.
CIt will silently fail and return empty data without errors.
DIt will fetch data but expose database credentials to the user.
Attempts:
2 left
💡 Hint

Remember where client components run and what environment they have.

state_output
advanced
2:00remaining
What is the rendered output of this Next.js Server Component with database access?

Given the following Next.js Server Component code that fetches user names from a database, what will be rendered?

NextJS
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>
  );
}
A<ul><li>Alice</li><li>Bob</li><li>Carol</li></ul>
B<ul><li>undefined</li><li>undefined</li></ul>
C<ul></ul>
DRuntime error: db.user.findMany is not a function
Attempts:
2 left
💡 Hint

Assume the database has users named Alice, Bob, and Carol.

📝 Syntax
advanced
2:00remaining
Which option correctly uses Next.js Server Actions to update a database record?

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?

A
export async function updateUserName(id, newName) {
  await fetch('/api/updateUser', { method: 'POST', body: JSON.stringify({ id, newName }) });
}
B
export const updateUserName = async (id, newName) =&gt; {
  await db.user.update({ where: { id }, data: { name: newName } });
};
C
export function updateUserName(id, newName) {
  db.user.update({ where: { id }, data: { name: newName } });
}
D
export async function updateUserName(id, newName) {
  await db.user.update({ where: { id }, data: { name: newName } });
}
Attempts:
2 left
💡 Hint

Server Actions must be async functions that perform server-side logic directly.

🔧 Debug
expert
3:00remaining
Why does this Next.js Server Component fail to fetch data from the database?

Examine the following Next.js Server Component code. It throws an error when trying to fetch data. What is the most likely cause?

NextJS
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>
  );
}
AThe function is not async, so awaiting the database call is missing, causing products to be a Promise, not an array.
BThe import path '@/lib/db' is incorrect and causes a module not found error.
CThe map function is used incorrectly; it should be forEach instead.
DThe database client does not support findMany method.
Attempts:
2 left
💡 Hint

Consider how async database calls work in JavaScript functions.

Practice

(1/5)
1. Why is database access important in a Next.js application?
easy
A. It allows the app to save and retrieve changing data securely.
B. It makes the app load faster by skipping data storage.
C. It replaces the need for any server-side code.
D. It only helps with styling the user interface.

Solution

  1. Step 1: Understand the role of database access

    Database access lets the app save and get data that changes over time, like user info or posts.
  2. Step 2: Connect to Next.js usage

    Next.js uses server-side code to safely handle database calls, ensuring data is secure and fast to access.
  3. Final Answer:

    It allows the app to save and retrieve changing data securely. -> Option A
  4. Quick Check:

    Database access = save and retrieve data [OK]
Hint: Database access means saving and getting data safely [OK]
Common Mistakes:
  • Thinking database access is only for styling
  • Believing it replaces server-side code
  • Assuming it makes the app load without data
2. Which Next.js file is the best place to put database access code?
easy
A. Inside a React client component's event handler
B. Directly inside the CSS files
C. In a server component or API route
D. In the public folder for static assets

Solution

  1. Step 1: Identify where database calls should run

    Database access should happen on the server side to keep data safe and avoid exposing secrets.
  2. Step 2: Match with Next.js structure

    Server components and API routes run on the server, so they are the right place for database code.
  3. Final Answer:

    In a server component or API route -> Option C
  4. Quick Check:

    Server code = database access place [OK]
Hint: Put database code in server components or API routes [OK]
Common Mistakes:
  • Putting database code in client components
  • Trying to access database in CSS or public folder
  • Exposing database secrets in client code
3. What will this Next.js server component do?
import { db } from '@/lib/db';

export default async function Page() {
  const users = await db.user.findMany();
  return (
    <ul>
      {users.map(user => <li key={user.id}>{user.name}</li>)}
    </ul>
  );
}
medium
A. Render a list of user names fetched from the database
B. Throw an error because db.user.findMany() is invalid
C. Render an empty list because users is undefined
D. Show a loading spinner indefinitely

Solution

  1. Step 1: Understand the database call

    The code calls db.user.findMany() to get all users from the database asynchronously.
  2. Step 2: Analyze the rendering

    The users array is mapped to list items showing each user's name inside an unordered list.
  3. Final Answer:

    Render a list of user names fetched from the database -> Option A
  4. Quick Check:

    db call + map users = list output [OK]
Hint: Async db calls return data to render lists [OK]
Common Mistakes:
  • Assuming db.user.findMany() is invalid syntax
  • Thinking users is undefined without await
  • Expecting a loading spinner without client code
4. Identify the error in this Next.js API route accessing a database:
export default function handler(req, res) {
  const users = db.user.findMany();
  res.status(200).json(users);
}
medium
A. db.user.findMany() is not a valid method
B. Using res.status instead of res.send
C. API routes cannot return JSON
D. Missing async/await for the database call

Solution

  1. Step 1: Check database call usage

    db.user.findMany() returns a promise, so it must be awaited or handled asynchronously.
  2. Step 2: Fix the handler function

    The handler should be async and await the database call before sending the response.
  3. Final Answer:

    Missing async/await for the database call -> Option D
  4. Quick Check:

    Async db calls need await [OK]
Hint: Always await async database calls in API routes [OK]
Common Mistakes:
  • Forgetting async keyword on handler
  • Not awaiting the promise from db calls
  • Confusing res.status with res.send usage
5. You want to show a list of posts with their authors' names in a Next.js server component. Which approach correctly handles database access to avoid slow page loads?
Option A:
const posts = await db.post.findMany({ include: { author: true } });
return posts.map(p => <div key={p.id}>{p.title} by {p.author.name}</div>);

Option B:
const posts = await db.post.findMany();
const authors = await db.user.findMany();
return posts.map(p => <div key={p.id}>{p.title} by {authors.find(a => a.id === p.authorId).name}</div>);

Option C:
Fetch posts on client side and authors on server side separately.

Option D:
Render posts without author names to speed up loading.
hard
A. Fetch posts and authors separately and match in code
B. Use a single query with include to fetch posts and authors together
C. Split fetching between client and server components
D. Skip author names to improve speed

Solution

  1. Step 1: Analyze database query efficiency

    Use a single query with include to fetch posts and authors together, reducing database calls and speeding up loading.
  2. Step 2: Compare other options

    Fetch posts and authors separately and match in code makes two queries, which is slower. Split fetching between client and server components causes complexity. Skip author names to improve speed loses important info.
  3. Final Answer:

    Use a single query with include to fetch posts and authors together -> Option B
  4. Quick Check:

    One query with include = faster load [OK]
Hint: Fetch related data in one query using include [OK]
Common Mistakes:
  • Making multiple separate queries instead of one
  • Fetching data on client causing slower loads
  • Removing needed info to speed up page