("[object Promise]") cannot be serialized as JSON

Viewed 6220

Full error:

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

I am trying to call one of my functions that retrieves some data from an API endpoint however when trying to pass this data to props I get an error. I am not exactly sure what I am doing wrong as the fetch call works if its within GetStaticProps but I want all my logic for fetch calls to exist within a separate js page to reduce redundancies, however when doing so this error is created.

export async function getStaticProps() {

let b = WordpressService.getPageByIdTest(50);

return {
    props: {
        b: b,
    }, 
    revalidate: 30     
}

}

const WordpressService = {
    async getPageByIdTest(id) {
    
        const resIndexPage = await fetch(`${url}pages/${id}`);
        const indexPageData = await resIndexPage.json();

        return indexPageData;
    }
}
2 Answers

I was going over the latest version of nextjs and I did notice that the demo was odd when I ran it. Specifically, I got this error when running their example:

Error: Additional keys were returned from getStaticProps. Properties intended for your component must be nested under the props key, e.g.

export async function getSortedPostsData() {
  // Instead of the file system,
  // fetch post data from an external API endpoint
  const res = await fetch('..')
  return res.json()
}

This is not exactly your issue but assigning the props object via res.json() also caused the same error you are experiencing.

So, for me, using node 15 I changed my api call to:

export async function getStaticProps() {
    const url = `https://my-url`
    const result = await fetch(url)
    return { props: {
      result: await result.json()
    }}
}

And this solved my problem. So Ivar's comment looks correct - await the result and then in my case I had to also await the json result from node-fetch so that the promises completed properly.

Related