본문 바로가기
Frontend/Next.js

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

by 디스코비스킷 2024. 12. 11.
반응형

포스트상세페이지([id].tsx)에서 getServerSideProps에서 url에서 id를 받아(query)
id로 getDoc 한개의 포스트를 조회해서 가져오는데
createdAt이라는 타임스탬프 타입 속성이 return할때 에러가 남.

  return {
    props: {
      ...data,      
    },
  };

이렇게 작성했더니

Reason: object ("[object Date]") cannot be serialized as JSON. Please only return JSON serializable data types
createdAt: createdAt ? JSON.parse(JSON.stringify(createdAt)) : null,

 

이런 에러가 남.

 

 

createdAt가 타임스탬프라서 json 파싱해서 리턴햇는데 (createdAt: JSON.parse(JSON.stringify(createdAt)))
createdAt.toDate().toLocaleDateString()이렇게 출력하면

 

TypeError: createdAt.toDate is not a function

 

이런 에러가 났다.

에러 원인

createdAtJSON.parse(JSON.stringify(createdAt))로 변환하면, Firestore의 Timestamp 객체가 일반적인 JSON 객체로 변환되기 때문에 toDate 메서드를 사용할 수 없다. createdAtDate 객체로 변환하려면 getServerSideProps에서 직렬화 전에 변환해야 한다.

올바른 처리 방법

1. getServerSideProps에서 Date 객체로 변환

createdAt을 Firestore의 Timestamp에서 Date로 변환한 후 문자열로 직렬화한다.

export const getServerSideProps = async (context) => {
  const doc = await getDoc(docRef);
  const data = doc.data();

  return {
    props: {
      post: {
        ...data,
        createdAt: createdAt.toDate().toISOString(),
      },
    },
  };
};
  • toDate()를 호출하여 Date 객체로 변환.
  • toISOString()으로 문자열화하면 JSON 직렬화가 가능하다.

2. 클라이언트에서 toLocaleDateString 사용

직렬화된 createdAt을 클라이언트에서 다시 Date 객체로 변환하여 로컬 날짜 형식으로 출력한다.

const Post = ({ post }) => {
  const createdAt = post.createdAt ? new Date(post.createdAt) : null;

  return (
    <div>
      <h1>{post.title}</h1>
      <p>{createdAt.toLocaleDateString()}</p>
    </div>
  );
};

정리

  • getServerSideProps에서 Firestore Timestamp를 직렬화하려면 toDate()로 변환 후 문자열화해야 한다.
  • 클라이언트에서 Date 객체로 다시 변환한 후 날짜를 원하는 형식으로 출력한다.
반응형

최근댓글

최근글

© Copyright 2024 ttutta