In this lesson, we are going to discuss how to fetch data in various parts of a Next.js application, including API routes, server actions, server components, as well as client components. We'll also introduce and compare two data fetching patterns, sequential fetching and parallel fetching.
Just in case you need a refresher on concepts such as API routes, server actions, server components, and client components, here is a brief review:
- Routes: Next.js implements a file based routing system, the files and folders inside the app directory maps to the routes to access the webpages and API endpoints.
- Pages: The webpage is defined by a
page.jsx
file.- Server Components: By default, the webpages are rendered on the server to provide better performance, faster loading time, and better user experience.
- Client Components: You can opt into client side rendering using a
"use client"
directive, giving access to React features such as state management, context, reducers, and more. Injecting interactivity into you web app.
- API Route Handlers: The API endpoint is defined by a
route.js
file. - Server Actions: A piece of code that can be used inside server or client component, but will be executed on the server. Most commonly used for form handling, allows you to submit the form without creating a dedicated API endpoint.
Fetching data on the server from API
The most commonly used method for data fetching is by using the fetch()
API. It is the default interface for making HTTP requests using JavaScript, and also processing the responses. For example:
1export default async function Page() {
2 const res = await fetch("https://dummyjson.com/users");
3 const data = await res.json();
4 return (
5 <ul>
6 {data.users.map((user) => (
7 <li key={user.id}>
8 {user.firstName} {user.lastName}
9 </li>
10 ))}
11 </ul>
12 );
13}
The fetch()
API allows you to set extra options, including:
- The
method
option allows you to specify the HTTP method used to send the request, such asGET
,POST
,PUT
, orDELETE
. - The
body
option allows you to include the request payload, often in formats like JSON, which the API endpoint can process to handle the request. - The
headers
option allows you to define additional metadata for the request, such asContent-Type
to specify the media type of the request body, orAuthorization
to include authentication tokens.
1const res = await fetch("https://dummyjson.com/users", {
2 method: "POST",
3 body: JSON.stringify({
4 firstName: "John",
5 lastName: "Doe",
6 email: "john@thedevspace.io",
7 }),
8 headers: {
9 "Content-Type": "application/json",
10 },
11});