Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am using Prisma and Next.js. 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,
    },
  };
};

As you can see in this image it is fetching as well as printing the content.

enter image description here

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.
like image 654
richinrix Avatar asked Sep 09 '25 18:09

richinrix


2 Answers

If you're using TypeScript, you can't change the type of createdAt to a string or number. This won't work:

newsLetter.createdAt = newsLetter.createdAt.toString();
// Error: Type 'string' is not assignable to type 'Date'.

Instead, you can use JSON.stringify inside JSON.parse to create a serializable object:

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

  return {
     props: {
        newsLetters: JSON.parse(JSON.stringify(newsLetters)) // <===
     }
  }
}
like image 138
Aidin53 Avatar answered Sep 12 '25 09:09

Aidin53


You can use Blitz's superjson package to get this working. They have instructions at https://github.com/blitz-js/superjson#using-with-nextjs:

Using with Next.js

The getServerSideProps, getInitialProps, and getStaticProps data hooks provided by Next.js do not allow you to transmit Javascript objects like Dates. It will error unless you convert Dates to strings, etc.

Thankfully, Superjson is a perfect tool to bypass that limitation!

Next.js SWC Plugin (experimental, v12.2 or above)

Next.js SWC plugins are experimental, but promise a significant speedup. To use the SuperJSON SWC plugin, install it and add it to your next.config.js:

yarn add next-superjson-plugin
// next.config.js
module.exports = {
  experimental: {
    swcPlugins: [
      [
        'next-superjson-plugin',
        {
          excluded: [],
        },
      ],
    ],
  },
} 
like image 41
chipit24 Avatar answered Sep 12 '25 09:09

chipit24