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.
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.
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)) // <===
}
}
}
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
, andgetStaticProps
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: [], }, ], ], }, }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With