Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error serializing Next.js in getStaticProps function?

I'm using getStaticProps() function and I get this error for no reason:

Error: Error serializing .posts[0] returned from getStaticProps in "/". Reason: object ("[object Object]") cannot be serialized as JSON. Please only return JSON serializable data types.

I'm also using a mongoDb database, the connectDb() function runs the mongoose.connect() function and connects to the database. also, the console.log()s return valid JSON format data, I don't know what is causing this issue, here is my code:

export const getStaticProps: GetStaticProps = async (
  context: GetStaticPropsContext
) => {
  await connectDb()
  const count = await PostModel.countDocuments()
  const posts = await PostModel.find()
  console.log(posts)
  console.log(count)
  return {
    props: { posts: posts, count: count },
    revalidate: 10,
  }
}
like image 498
Dastan Avatar asked Mar 23 '21 09:03

Dastan


People also ask

Why can't I serialize the profile data returned from getstaticprops?

The error: Server Error Error: Error serializing .profileData returned from getStaticProps in "/profile/ [slug]". Reason: undefined cannot be serialized as JSON.

How do I use getstaticprops with next?

When a page with getStaticProps is pre-rendered at build time, in addition to the page HTML file, Next.js generates a JSON file holding the result of running getStaticProps. This JSON file will be used in client-side routing through next/link or next/router.

Why can't I serialize undefined as JSON?

Reason: undefined cannot be serialized as JSON. Please use null or omit this value. I don't know what could cause this though. Show activity on this post. Add JSON.stringify when calling an asynchronous function that returns an object. Try modifying your getStaticProps function like this.

What is the getstaticprops API reference?

The getStaticProps API reference covers all parameters and props that can be used with getStaticProps. As getStaticProps runs only on the server-side, it will never run on the client-side. It won’t even be included in the JS bundle for the browser, so you can write direct database queries without them being sent to browsers.


1 Answers

Use lean it will convert in a plain JavaScript object.

const posts = await PostModel.find().lean();

or you can try serialization via .toJSON

like image 59
Mohammad Ali Rony Avatar answered Oct 24 '22 06:10

Mohammad Ali Rony