[Fixed]-How to fetch data server-side in the latest Next.js? Tried getStaticProps but it's not running and getting undefined

14👍

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 (used when you answer yes to the last question shown in the below image) we have Server Components, where you can fetch data directly in the component body as shown in the below code snippet (please read the comments):

enter image description here

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

/*
 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`.
*/
export default async function Component({ params, searchParams }) {
  /* 
    This request should be cached until manually invalidated.
    Similar to `getStaticProps`.
    `force-cache` is the default and can be omitted.
  */
  const staticData = await fetch(`https://...`, { cache: "force-cache" });

  /*
    This request should be refetched on every request.
    Similar to `getServerSideProps`.
  */
  const dynamicData = await fetch(`https://...`, { cache: "no-store" });

  /* 
    This request should be cached with a lifetime of 10 seconds.
    Similar to `getStaticProps` with the `revalidate` option.
  */
  const revalidatedData = await fetch(`https://...`, {
    next: { revalidate: 10 },
  });

  return "...";
}

That has been said, you can get data without fetch(), using any library, or even directly talking to your database with an ORM, in which case you can use Route Segment Config:

// layout.js OR page.js OR route.js 👈🏽

import prisma from "./lib/prisma";

/*
  Keep one of the possibilities shown below (there are more on the doc), 
  depending on your needs. 
*/

export const revalidate = 10; // If you want to revalidate every 10s
// OR
export const dynamic = "force-dynamic"; // If you want no caching at all
// ...

async function getPosts() {
  const posts = await prisma.post.findMany();
  return posts;
}

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

5👍

This StackOverFlow question (Can't use GetStaticProp in Next.js 13) was closed as a duplicate of this question.

To help rookies like me:

You can’t use getStaticProps in Nextjs 13 (using App Router).

The new way is to just use fetch. You can read more about fetch here.

async function getArtist(username: string) {
  const res = await fetch(`https://api.example.com/artist/${username}`)
  return res.json()
}

This image compares the old and new way of doing things. image source

enter image description here

Because the new default is to cache all fetch requests (unless they opt out) calling fetch in a static component has the same effect as getStaticProps. You can read more about Static Data Fetching here.

So to be clear this normal fetch request:

//Similar to 'getStaticProps' when used in a static rendering component
fetch(API_URL)

is the same as this ‘force-cache’ request:

//This request would be cached until manually invalidated. 
//Similar to 'getStaticProps'
//Use this type of fetching for data that does not change often.
 
fetch(API_URL, { cache: 'force-cache' })

More info about the default caching here.

Why did you want to use getStaticProps in the first place?

To help the rookies, who find getStaticProps in a tutorial and find there way here, the reason you want to use getStaticProps is you want to render a page once, and then send that page to every user.

This makes your page faster, send less code to your users, and is better for SEO etc.

But what if you need to get some data to render that page once? Before Nextjs 13 you would use getStaticProps.

Now you fetch in a static component. The effect is the same.

And that effect is, once (at build time when you deploy your project) Nextjs will go get some data, then use that data to render a page, and then send that pre-rendered page to everyone who needs it.

If you need to statically generate a bunch of pages using dynamic routes, the generateStaticParams function can be used to generate routes at build time instead of on-demand at request time for dynamic routes. info here.

For rookies, if you don’t know what dynamic routes are, just use fetch. 🙂

2👍

In app directory you cannot use getServerSideProps, getStaticProps,getInitialProps like methods for data fetching. Instead of this with server component you can make component it self async and fetch data in component body direclty. Futhur more you can pass the data to client compoent for rendering service.

export async function getData(){
const res = await fetchData();
const data = res.json()
return data

} }

Now you can call this async function in your main component

export async function(){
const data =await getData()
return (<ClientComponent data />)
}

Leave a comment