Front-end/Next.js

[노마드코더] #7 Catch All, 404

성중 2022. 2. 24. 18:49

Catch All

catch-all url을 사용한다면 url로 데이터를 전달할 때 생겼던 문제들을 해결할 수 있다

 

[id].js의 파일 명을 [...params].js로 변경해준다

 

[pages/movies/index.js]

  onClick={() =>
    router.push(
      `/movies/${movie.original_title}/${movie.poster_path}/${movie.id}`
    )
  }

'movies/제목/포스터/아이디' 이런 식으로 다 url로 보내고 router를 콘솔로 찍어보면..

 

query에 변수(params)가 url의 모든 요소를 담는 배열로 넘어온다 !

[pages/movies/[params].js]

import Seo from "../../components/Seo";
import { useRouter } from "next/router";
 
export default function Detail() {
  const router = useRouter();
  console.log(router);
  const [title, poster] = router.query.params || [];
  return (
    <div>
      <Seo title={title} />
      <h4>{title}</h4>
      <img src={`https:/image.tmdb.org/t/p/w500/${poster}`} />
    </div>
  );
}

이렇게 변수로 받아서 사용할 수 있다

* hydration 전까지 오류가 발생하지 않도록 조건부로 초기값을 넣어줬다

 

데이터가 서버에서 넘어오기 때문에, 해당 데이터에도 SSR을 적용해 SEO를 구현할 수 있다

import Seo from "../../components/Seo";
 
export default function Detail({ params }) {
  const [title, poster] = params;
  return (
    <div>
      <Seo title={title} />
      <h4>{title}</h4>
      <img src={`https:/image.tmdb.org/t/p/w500/${poster}`} />
    </div>
  );
}
 
export function getServerSideProps({ params: { params } }) {
  return {
    props: {
      params,
    },
  };
}

이 경우, API를 fetch하는 것이 아니기 때문에 딜레이도 없고, 초기값이 없어도 된다 !

(그런데 catch-all url을 어떻게 masking 하는지는 모르겠다 ..)

 

404

404 페이지를 커스텀하려면 pages 폴더에 404.js를 생성하면 된다 !

 

[pages/404.js]

export default function NotFound() {
  return "404";
}

 

본 내용은 노마드코더의 'NextJS 시작하기'를 바탕으로 작성되었습니다