Home > Web Front-end > JS Tutorial > body text

How to Fetch Data Server-Side in Next.js with Server Components and Beyond?

Mary-Kate Olsen
Release: 2024-11-25 17:04:14
Original
230 people have browsed it

How to Fetch Data Server-Side in Next.js with Server Components and Beyond?

Next.js Server-Side Data Fetching Using getStaticProps and Beyond

Issue:
In a Next.js application utilizing Django Rest Framework, data fetching from a REST API results in undefined values and runtime errors when mapping the data.

Explanation:
Next.js methods like getStaticProps are specifically designed for server-side data retrieval and only function effectively within the pages directory. However, in the latest versions of Next.js, data can be fetched directly within server components located inside the app directory.

Resolution:
To resolve this issue and perform server-side data fetching in the latest Next.js, consider the following options:

Using Server Components:

  • Implement server-side data fetching within the component body, as seen in the code snippet.
  • This approach enables direct access to headers and cookies for data retrieval.

Using Route Segment Config (for Database Interactions):

  • Configure route segments to cache data with desired lifespans (e.g., 10 seconds) or disable caching altogether.
  • This method allows for flexibility in data fetching and caching strategies, including direct interactions with databases using ORMs.

Code Snippets (Server Components):

// page.js
export default async function Page() {
  const staticData = await fetch(`https://...`, { cache: "force-cache" });
  const dynamicData = await fetch(`https://...`, { cache: "no-store" });

  return "...";
}
Copy after login

Code Snippets (Route Segment Config):

// layout.js OR page.js OR route.js
export const revalidate = 10;
Copy after login
// ...
async function getPosts() {
  const posts = await prisma.post.findMany();
  return posts;
}

export default async function Page() {
  const posts = await getPosts();
  // ...
}
Copy after login

By implementing these solutions, you can effectively fetch data from servers and handle caching strategies within Next.js, even when working with server components.

The above is the detailed content of How to Fetch Data Server-Side in Next.js with Server Components and Beyond?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template