Home  >  Article  >  Web Front-end  >  How do you Fetch Data Server-Side in Next.js 13 and Beyond?

How do you Fetch Data Server-Side in Next.js 13 and Beyond?

Barbara Streisand
Barbara StreisandOriginal
2024-11-16 19:18:03763browse

How do you Fetch Data Server-Side in Next.js 13 and Beyond?

Fetching Data Server-Side in Next.js

Server-Side Data Fetching in Next.js 13 and Beyond

In recent versions of Next.js, the "getStaticProps" and "getServerSideProps" methods were phased out, leaving developers wondering how to fetch data server-side in modern Next.js applications.

Introducing Server Components

With Next.js 13 and up, the introduction of Server Components offers a new way to fetch data server-side. Unlike traditional page components, Server Components can directly access data-fetching logic within the component's body.

Example in Server Components

The following code snippet illustrates how to fetch data server-side within a Server Component:

export default async function Component() {
  // Fetch server-side data with caching options
  const staticData = await fetch(`https://...`, { cache: "force-cache" });
  const dynamicData = await fetch(`https://...`, { cache: "no-store" });
  const revalidatedData = await fetch(`https://...`, { next: { revalidate: 10 } });

  return "...";
}

Route Segment Configuration

In addition to Server Components, Next.js provides Route Segment Configuration. This allows developers to control caching behavior for specific routes or pages, even during server-side data fetching.

Example in Route Segment Configuration

This example shows how to configure route-specific caching using Route Segment Configuration:

// layout.js OR page.js OR route.js ??

export const revalidate = 10; // Revalidate every 10s
// ...

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

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

Statement:
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