0
0
NextJSframework~30 mins

Server component database queries in NextJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Server Component Database Queries in Next.js
📖 Scenario: You are building a simple blog homepage using Next.js. The blog posts are stored in a database. You want to fetch the posts on the server side and display them in a list.
🎯 Goal: Create a Next.js server component that queries a database for blog posts and renders their titles in a list.
📋 What You'll Learn
Use a server component in Next.js
Create a mock database query function
Fetch data inside the server component
Render the list of blog post titles
💡 Why This Matters
🌍 Real World
Fetching data on the server side is common in web apps to improve performance and SEO. Server components in Next.js let you do this easily.
💼 Career
Understanding server components and database queries is essential for building modern React apps with Next.js, a popular framework in the industry.
Progress0 / 4 steps
1
Set up mock blog posts data
Create a constant called posts that is an array of objects. Each object should have id and title properties. Use these exact entries: { id: 1, title: 'Hello World' }, { id: 2, title: 'Learning Next.js' }, { id: 3, title: 'Server Components' }.
NextJS
Need a hint?

Use const posts = [ ... ] with objects inside the array.

2
Create a mock database query function
Create an async function called getPosts that returns the posts array.
NextJS
Need a hint?

Define async function getPosts() { return posts; }

3
Fetch posts inside the server component
Create a default exported async function component called BlogList. Inside it, call await getPosts() and store the result in a variable called allPosts.
NextJS
Need a hint?

Use export default async function BlogList() { const allPosts = await getPosts(); }

4
Render the list of blog post titles
Inside the BlogList component, return a <ul> element. Use allPosts.map with post as the iterator to create <li> elements. Each <li> should have a key attribute set to post.id and display post.title.
NextJS
Need a hint?

Return JSX with <ul> and map allPosts to <li key={post.id}>{post.title}</li>.