Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reason: `object` ("[object Date]") cannot be serialized as JSON. Please only return JSON serializable data types

I am using prisma and nextJS. When i try to retrieve the content from prisma in getStaticProps it does fetch the data but i can’t pass it on to the main component.

export const getStaticProps = async () => {
  const prisma = new PrismaClient();
  const newsLetters = await prisma.newsLetters.findMany();
  console.log(newsLetters);

  return {
    props: {
      newsLetters: newsLetters,
    },
  };
};

[![enter image description here][1]][1]

As you can see in this image it is fetching as well as printing the content.
[1]: https://i.stack.imgur.com/d34op.png

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

But when i pass I get the following error for passing it as props

Reason: `object` ("[object Date]") cannot be serialized as JSON. Please only return JSON serializable data types.

>Solution :

Looks like nextJS doesn’t like serializing anything but scalar types for performance reasons. You can read more in this github issue. Best way you can handle this is that you convert your Date objects to UNIX timestamp before returning them.

// your data
let newsLetters = [
    {
        id: 'your-id',
        email: 'email@example.com',
        createdAt: new Date()
    }
];

// map the array
newsLetters.map(x => {
    x.createdAt = Math.floor(x.createdAt / 1000);
    return x;
})

// use newsLetters now
console.log(newsLetters);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading