Yasser Elsaid
Yasser Elsaid

Reputation: 1

getStaticPaths and getStaticProps work in development but the prop is undefined in build time

I am making an eCommerce platform using Next.js. In the product page, where I use dynamic routes, I used getStaticProps to fetch my product and getStaticPaths to generate the paths to the products that should be statically generated. This works perfectly in development mode but the project does not build. The product prop which is passed from getStaticProps to the page component is undefined in build time.

This is the error I get when trying to build:

Error occurred prerendering page "/product/[id]". Read more: https://err.sh/next.js/prerender-error TypeError: Cannot destructure property 'name' of 'product' as it is undefined.

function ProductPage({ product}) {
// product is defined in development but undefined when trying to build
const {
name,
price,
} = product;
// The rest of the component
}

export const getStaticPaths = async () => {
  connectDb();

  const products = await Product.find();
  const paths = products.map(product => ({
    params: { id: product._id.toString() },
  }));
  return {
    paths,
    fallback: true,
  };
};

export const getStaticProps = async ({ params }) => {
  connectDb();
  const { id } = params;
  try {
    // getting the product
    const product = await Product.findOne({ _id: id });
    return {
      props: {
        product: JSON.parse(JSON.stringify(product)),
      },
    };
  } catch (err) {
    console.log(err);
    return {
      props: {
        product: {},
      },
    };
  }
};

export default ProductPage;

why is the product prop defined in development mode but undefined in build time, and how can I fix this?

Upvotes: 0

Views: 1589

Answers (2)

KSoenandar
KSoenandar

Reputation: 183

I recently encountered the exact same issue. I'm not sure what you have put in your //the rest of the component section but I noticed in the getStaticPaths function you specify fallback: true. Make sure you handle this in the page component by adding a skeleton or a loading indicator for pages that didn't yet exist at build time. That did the trick for me.

Upvotes: 3

KukicAdo
KukicAdo

Reputation: 43

Looking over the code it seems like the product is undefined likely because the code in the try block failed to return data (or you didn't find a matching document in the MongoDB database?). Can you verify that no error occurs?

This can happen if you're passing the id param as "string" while in your MongoDB database the _id field is of type "ObjectID". You can remedy that by converting the "id" string to an ObjectID using the MongoDB package.

Upvotes: 0

Related Questions