Mayank Kumar Chaudhari
Mayank Kumar Chaudhari

Reputation: 18538

`throw new Error('Failed to load static props')` when setting `fallback: true` in `getStaticPaths` in Next.JS

Refer to discussion here. I faced similar error. Everything worked fine when fallback is set to false. However, when fallback is set to true, next js throws error

 throw new Error('Failed to load static props')

Upvotes: 6

Views: 18297

Answers (3)

Harita Ravindranath
Harita Ravindranath

Reputation: 470

Here's how I solved this issue using notFound: true inside getStaticProps.

export async function getStaticProps({ params: { id } }) {

  const res = await fetch(`{{api}}/items?id=${id}`);
  const item = await res.json();

  const notFound = item[0] ? false : true;

  return {
    props: {
      item: item[0]
    },
    revalidate: 10,
    notFound
  };
}

Upvotes: 1

orlyohreally
orlyohreally

Reputation: 460

I have found my answer here https://github.com/vercel/next.js/discussions/11862:

Your getStaticProps should return a boolean like notFound: true, and your page can render a 404 page or the next/error page. This would allow the page to eventually become real (if the missing slug is created in backend).

Upvotes: 1

Mayank Kumar Chaudhari
Mayank Kumar Chaudhari

Reputation: 18538

After lot of searching and trial and error, I found out that the error was because of the exceptions throws inside getStaticProps.

To solve this issue all I did is to use try-catch block.

export async function getStaticProps({ params }) {
  let data = null;
  try {
    data = await getData(params.slug);
  } catch (err) { };

  return {
    props: {
      data,
    },
  };

And when rendering your can use

if(props.data) return (<your-jsx-here></your-jsx-here>)
else return <div>Any message if you want</div>

Upvotes: 10

Related Questions