[nextjs] nextjs error 모음

dev stefanCho·2021년 12월 18일
0

nextjs

목록 보기
2/9

next js로 작업하면서 발생하는 에러모음

A required parameter (postId) was not provided as a string in getStaticPaths

Server Error
Error: A required parameter (postId) was not provided as a string in getStaticPaths for /building/[postId]

원인 1

  • getStaticPaths의 params: { postId: 여기 타입이 string이어야만 함 }
export const getStaticPaths: GetStaticPaths = async () => {
  const posts = await fetch('https://jsonplaceholder.typicode.com/posts').then(
    (r) => r.json()
  );
  return {
    paths: posts.map((post: any) => {
      return {
        params: {
          postId: post.id, // post.id.toString()으로 에러해결
        },
      };
    }),
    fallback: false,
  };
};

원인 2

dynamic file name과 params의 property값이 일치해야함

export const getStaticPaths: GetStaticPaths = async () => {
  const posts = await fetch('https://jsonplaceholder.typicode.com/posts').then(
    (r) => r.json()
  );
  return {
    paths: posts.map((post: any) => {
      return {
        params: {
          postId: post.id.toString(),
        },
      };
    }),
    fallback: false,
  };
};

위와 같은 경우라면, file명이 [postId].ts이어야 함

getStaticPaths is required for dynamic SSG pages

Server Error
Error: getStaticPaths is required for dynamic SSG pages and is missing for '/building/[Id]'.
Read more: https://nextjs.org/docs/messages/invalid-getstaticpaths-value

dynamic filename으로 만들고, getStaticPaths가 없는 경우 발생함
예를 들어 파일이름은 [id].tsx인데, getStaticPaths가 없으면, 다이나믹하게 fetch를 할수가 없는 상태임. 파일이름을 []를 빼고 그냥 string으로 만들것

undefined cannot be serialized as JSON

  • npm run build에서 발생
Reason: `undefined` cannot be serialized as JSON. Please use `null` or omit this value.

return object에서 props내에 있는 property value가 undefined인 경우 발생했다.

export const getStaticProps: GetStaticProps = async (context) => {
  const params = context.params!;
  const filePath = getBuildingPath();
  const data: Array<Building> = extractBuilding(filePath);
  return {
    props: {
      building: data.find(({ id }) => id === Number(params.id)), // building이 undefined인 경우 발생
    },
  };
};

return 부분에 nullish operator로 해결했다. (아래코드)

  return {
    props: {
      building: data.find(({ id }) => id === Number(params.id)) ?? {}, // undefined인 경우 기본값으로 {}
    },
  };

Error serializing

Error: Error serializing `.event` returned from `getStaticProps` in "/events/[eventId]".
Reason: `undefined` cannot be serialized as JSON. Please use `null` or omit this value.

getStaticProps의 return에서 props가 object가 아닌 경우 발생함

Could not find a declaration file for module 'react-dom'.

tsx파일에서 발생한다. react-dom type 정의를 못찾아서 그런것이니 install 해준다.

npm i @types/react-dom
profile
Front-end Developer

1개의 댓글

comment-user-thumbnail
2023년 3월 3일

선생님 답답했던 문제가 있었는데 너무 감사합니다!

답글 달기