Next.js 14.2.5 extends the native fetch Web API, allowing you to configure caching and revalidating behavior for each fetch request on the server. This extends fetch to automatically memoize fetch requests while rendering a React component tree. In this blog, we’ll explore how to fetch data using fetch with async/await and display it in a Next.js application. We’ll use a simple example to illustrate the process.
Fetching Data on the Server with fetch
Next.js allows you to use fetch in various places, including Server Components, Route Handlers, and Server Actions. In our example, we’ll fetch data from the jsonplaceholder.typicode.com API and display a list of posts.
Example Code
Here’s a step-by-step guide to fetching and displaying data in Next.js 14.2.5:
Create a Function to Fetch Data
We’ll create an asynchronous function getData to fetch data from the API. If the response is not okay, we’ll throw an error. Otherwise, we’ll return the JSON data.
async function getData() {
const res = await fetch('https://jsonplaceholder.typicode.com/posts')
if (!res.ok) {
throw new Error('Failed to fetch data')
}
return res.json()
}
Use the Fetch Function in the Home Component
We’ll use the getData function inside our Home component. This component will fetch the data and render it. The fetched data will be mapped to display each post’s title and body.
export default async function Home() {
const data = await getData()
return (
<main className="flex min-h-screen p-20 gap-20 flex-col ">
<div className="py-5 px-2 bg-slate-50 rounded-md flex items-center justify-center">
<h1 className="text-4xl text-green-900">Posts</h1>
</div>
{data.map((post) => (
<div key={post.id} className="flex py-5 px-2 bg-slate-50 rounded-md flex-col ">
<div className="flex flex-row gap-4 ">
<h2 className="text-black">Title: </h2><span className="text-black">{post.title}</span>
</div>
<div className="flex flex-row gap-4">
<p className="text-black">Body: </p><span className="text-black">{post.body}</span>
</div>
</div>
))}
</main>
);
}
Rendering the Output
When you run this code, the fetched data will be displayed in a structured format, with each post’s title and body presented in a clean and organized layout.
Output
The output of the above code will display a list of posts fetched from the API, formatted with titles and bodies.