Discover how connecting to a database turns static pages into living, breathing apps!
Why database access matters in NextJS - The Real Reasons
Start learning this pattern below
Jump into concepts and practice - no test required
Imagine building a website where you have to update user info, product lists, or comments by hand every time someone interacts with it.
You would have to change files manually and refresh pages to show new data.
Manually updating data is slow and prone to mistakes.
It's hard to keep data consistent and up-to-date for all users.
It also makes your site less interactive and less useful.
Database access lets your app read and write data automatically.
It keeps information fresh and shared across all users instantly.
This makes your website dynamic, interactive, and reliable.
const users = [{name: 'Alice'}, {name: 'Bob'}]; // manually update arrayconst users = await db.query('SELECT * FROM users'); // fetch from database
It enables building apps that respond to real-time data changes and user actions smoothly.
Think of an online store where product availability updates instantly as customers buy items.
Manual data updates are slow and error-prone.
Database access automates data management and sharing.
This makes apps dynamic, interactive, and user-friendly.
Practice
Solution
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.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.Final Answer:
It allows the app to save and retrieve changing data securely. -> Option AQuick Check:
Database access = save and retrieve data [OK]
- Thinking database access is only for styling
- Believing it replaces server-side code
- Assuming it makes the app load without data
Solution
Step 1: Identify where database calls should run
Database access should happen on the server side to keep data safe and avoid exposing secrets.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.Final Answer:
In a server component or API route -> Option CQuick Check:
Server code = database access place [OK]
- Putting database code in client components
- Trying to access database in CSS or public folder
- Exposing database secrets in client code
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>
);
}Solution
Step 1: Understand the database call
The code calls db.user.findMany() to get all users from the database asynchronously.Step 2: Analyze the rendering
The users array is mapped to list items showing each user's name inside an unordered list.Final Answer:
Render a list of user names fetched from the database -> Option AQuick Check:
db call + map users = list output [OK]
- Assuming db.user.findMany() is invalid syntax
- Thinking users is undefined without await
- Expecting a loading spinner without client code
export default function handler(req, res) {
const users = db.user.findMany();
res.status(200).json(users);
}Solution
Step 1: Check database call usage
db.user.findMany() returns a promise, so it must be awaited or handled asynchronously.Step 2: Fix the handler function
The handler should be async and await the database call before sending the response.Final Answer:
Missing async/await for the database call -> Option DQuick Check:
Async db calls need await [OK]
- Forgetting async keyword on handler
- Not awaiting the promise from db calls
- Confusing res.status with res.send usage
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.Solution
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.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.Final Answer:
Use a single query with include to fetch posts and authors together -> Option BQuick Check:
One query with include = faster load [OK]
- Making multiple separate queries instead of one
- Fetching data on client causing slower loads
- Removing needed info to speed up page
