How to fetch data server-side in the app directory of Next.js? Tried getStaticProps but it’s returning undefined

Methods like getServerSideProps and getStaticProps are for fetching data on the server but they only work for page components inside the pages folder (the initial way of setting up routes in Next.js).

Since Next.js 13, in the app directory we have Server Components, where you can fetch data directly in the component body. In your case, it would be something like this:

/*
  If you want to access headers or cookies while fetching data,
  you can use these functions:
*/
import { cookies, headers } from "next/headers";

/* 
   Depending on whether you are using dynamic routes or not, and the `cache` 
   option of `fetch`, you can mimic previous methods 
   like getStaticProps or getServerSideProps.
*/
async function getCampaigns() {
  const response = await fetch("http://127.0.0.1:8000/api/campaigns", { cache: "no-store" });
  const data = await response.json();
  return data;
}

/*
 If the below component is the default export of a `page.js` and you are using 
 dynamic routes, slugs will be passed as part of `params`, and 
 query strings are passed as part of `searchParams`.
 You can pass them to your data fetching function.
*/
export default async function Index({ params, searchParams }) {
  const data = await getCampaigns();
  return <div>{/* You can use data here. */}</div>;
}

For more, you can read App Router Incremental Adoption Guide.

Leave a Comment