imgyuzzzang

[NEXT JS] getServerSideProps는 Date 객체를 허락하지 않아,, 본문

computer science/에러로그

[NEXT JS] getServerSideProps는 Date 객체를 허락하지 않아,,

imgyuzzzang 2022. 11. 22. 20:45

츨처: https://github.com/vercel/next.js/issues/13209#issuecomment-633149650

세 줄 요약

  • object ("[object Date]") cannot be serialized as JSON. Please only return JSON serializable data types. 오류 발생
  • NextJS 에서는 getInitialProps, getServerSideProps, getStaticProps 의 리턴 값으로 plain Object만을 허용
  • 특정 (Date, Map, Set) 타입을 퍼포먼스 이슈로 인해 지원하지 않음

해결 방법

  1. JSON.parse(JSON.stringify(객체))사용

  2. safe-json-stringify 라이브러리 사용 (1번이랑 다를게 뭐지…?)

    import safeJsonStringify from 'safe-json-stringify';
    ...
    export async function getServerSideProps() {
        ...
      return {
        props: {
          JSON.parse(safeJsonStringify(객체))
        }
      };
    }
  3. next-superjson-plugin설치 + 넥스트 컨피그 설정

    // next.config.js
    module.exports = {
      experimental: {
        swcPlugins: [
          [
            'next-superjson-plugin',
            {
              excluded: [],
            },
          ],
        ],
      },
    }
Comments