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

Pyotato·2024년 1월 22일
0

해결: https://stackoverflow.com/questions/70449092/reason-object-object-date-cannot-be-serialized-as-json-please-only-ret

Prisma + Nextjs +ts 에서
메인 페이지에서 포스팅 날짜, 글쓴이 정보, 포스트 제목과 내용을 받아온 포스트를 가자오는 api에서 위와 같은 에러가 났다.



export interface PostProps {
  id: string;
  title: string;
  author: {
    name: string;
    email: string;
    image?: string;
  } | null;
  content: string;
  published: boolean;
  createdAt: Date;
  publishedAt?: Date;
}

import { GetStaticProps } from "next";
import React from "react";
import Layout from "../components/Layout";
import Post, { PostProps } from "../components/Post";
import prisma from "../lib/prisma";
export const getStaticProps: GetStaticProps = async () => {
  const feed = await prisma.post.findMany({
    where: { published: true },
    include: {
      author: {
        select: { name: true, image: true },
      },
    },
    orderBy: { publishedAt: "desc" },
  });
  return {
    props: { feed: JSON.parse(JSON.stringify(feed)) }, // props: {feed}
    revalidate: 3,
  };
};

type Props = {
  feed: PostProps[];
};

문제는 Date는 객체이기 때문에 json 시리얼라이징이 불가능했다.
따라서 stringify로 감싸주고 json 파싱을 통해 문제 해결

profile
https://pyotato-dev.tistory.com/ 로 이사중 🚚💨🚛💨🚚💨

0개의 댓글

관련 채용 정보