Reason: `object` ("[object Date]") cannot be serialized as JSON. Please only return JSON serializable data types
Full error message
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.Solutionsource: stackoverflow \u2197
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 protected]', createdAt: new Date() } ]; // map the array newsLetters.map(x => { x.createdAt = Math.floor(x.createdAt / 1000); return x; }) // use newsLetters now console.log(newsLetters);
API access
Get this solution programmatically \u2014 free, no authentication.
curl https://depscope.dev/api/error/71e873e1e39def2ee3ab494ce1881ef73b09ef3dc018e38aad665b4ba80c1423hash \u00b7 71e873e1e39def2ee3ab494ce1881ef73b09ef3dc018e38aad665b4ba80c1423