Prisma generated date type / Next.js and dates #4428
-
I'm still experimenting with Next.js together with Prisma using TypeScript. As the Next.js page props are serialized as a JSON object it does not support dates. Now I was looking at the Primas example using Next.js and I noticed that dates seem to be excluded, on purpose? Is this done on purpose? And is there small 'workaround' how to pass models with date using Next.js. |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 14 replies
-
Hey @marceloverdijk 👋 You're most probable facing an issue that Next.js has where it doesn't serialize the I would suggest reading the below discussions/issues and the workaround is to stringify the date first and then set them in props. |
Beta Was this translation helpful? Give feedback.
-
I converted the obj to json string then passed it to client. For other functions I converted the json to obj again in client. I hope Next.js add this ability later! |
Beta Was this translation helpful? Give feedback.
-
For anyone 'not-too-keen' on blitz reverse engineering exercise. I did some basic remapping like this:
|
Beta Was this translation helpful? Give feedback.
-
The following code works for me, and preserves the types. This is from SO, but don't have the source: type Overwrite<T, U> = Pick<T, Exclude<keyof T, keyof U>> & Pick<U, Extract<keyof U, keyof T>> extends infer O
? {
[K in keyof O]: O[K];
}
: never;
export const recursivelySerializeDatesInObject = <T extends { updatedAt?: Date; createdAt: Date }>(
obj: T
): Overwrite<T, { updatedAt: string; createdAt: string }> => {
const retObj: any = { ...obj };
if (obj.createdAt) {
retObj.createdAt = obj.createdAt.toISOString();
}
if (obj.updatedAt) {
retObj.updatedAt = obj.updatedAt.toISOString();
}
Object.keys(retObj).forEach((key) => {
if (retObj[key] && typeof retObj[key] === `object`) {
retObj[key] = recursivelySerializeDatesInObject(retObj[key]);
}
});
return retObj as any;
}; |
Beta Was this translation helpful? Give feedback.
Hey @marceloverdijk 👋
You're most probable facing an issue that Next.js has where it doesn't serialize the
Date
type.I would suggest reading the below discussions/issues and the workaround is to stringify the date first and then set them in props.
vercel/next.js#11993
vercel/next.js#11498