PrismaP
Prisma2y ago
10 replies
Florian

Type-safety for dates when returning DB entries as JSON

I used to use Prisma in server components where I don't need to do serialization.

Now I need to return DB entries from an API route handler in JSON form.

This means, the Date type of the Prisma model is not correct on the client anymore. JSONification turns the Date into a string.

What's the correct way to handle this on the client so I have type-safety?

const posts = await prisma.post.findMany({
  include: getPostWithReplyToInclude(user?.id),
  orderBy: {
    createdAt: "desc",
  },
  take: pageSize + 1,
  cursor: cursor ? { id: cursor } : undefined,
});

const nextCursor = posts.length > pageSize ? posts[pageSize].id : null;

const responseBody: PostsPage = {
  posts: posts.slice(0, pageSize),
  nextCursor,
};

return Response.json(responseBody);
Was this page helpful?