-
[toy blog service] Dynamic route를 가진 페이지에서 getStaticProps를 하려면 getStaticPaths가 필요하다!Web Dev/5. Projects 2021. 4. 13. 15:20728x90
nextjs.org/docs/basic-features/data-fetching#getstaticpaths-static-generation
여기서는 getStaticPaths가 무엇인지 다루어보겠다.
아래는 내가 getStaticPaths를 통해서 개발한 코드랑 화면이다.
import Head from "next/head"; import React from "react"; import { PostType } from "../../utils/types"; import { GetStaticProps, GetStaticPaths } from "next"; import { openJsonFile } from "../../utils/common"; export const getStaticPaths: GetStaticPaths = async () => { console.log("getStaticPaths"); return { paths: [ { params: { username: "hayoung" } }, // See the "paths" section below ], fallback: false, // See the "fallback" section below }; }; // Incremental Static Site Regeneration export const getStaticProps: GetStaticProps = async ({ params }) => { const jsonData = await openJsonFile(); const username = params.username as string; const data: PostType[] = jsonData.contents[username] || []; return { props: { data, }, // will be passed to the page component as props revalidate: 10, }; }; interface Props { data: PostType[]; } const UserHome: React.FC<Props> = ({ data }) => { return ( <div> <Head> <title>UserHome</title> <link rel="icon" href="/favicon.ico" /> </Head> <div>UserHome</div> <div> {data?.map((d, index: number) => { return ( <div key={index}> <h2>{d.title}</h2> <h5>{d.contents}</h5> </div> ); })} </div> </div> ); }; export default UserHome;
일단 위의 code는 fallback을 false로 해둔 것이다.
dynamic routes에서 static rendering을하려면 두가지 key는 꼭필요하다. 하나는 paths, 다른 하나는 fallback이다.
- getStaticPaths 설정하기
export const getStaticPaths: GetStaticPaths = async () => { return { paths: [ { params: { username: "hayoung" } }, // See the "paths" section below ], fallback: false, // See the "fallback" section below }; };
여기서 params에는 어떤 다이나믹 루트에대해서 static generation을 할지 선택하는 것이다. 여기의 params가 getStaticProps로 pass된다.
여기서 params에 username내용이 들어간다. 그래서 그에 해당하는 데이터를 가져올 수 있다. 다이나믹 경로에 대해서도 revalidate 옵션을 통해서 동일하게 Incremental Static Regeneration을 할 수 있다.
export const getStaticProps: GetStaticProps = async ({ params }) => { const jsonData = await openJsonFile(); const username = params.username as string; const data: PostType[] = jsonData.contents[username] || []; return { props: { data, }, // will be passed to the page component as props revalidate: 10, }; };
- fallback option:
젤 상단에서도 보면 404에러가 뜨는 경우는 getStaticPaths에 없는 경로로 접근할때이다(fallback: false 인 경우). Fallback이 false인 경우 미리 지정하지 않은 다이나믹 루트로 가려는 경우 페이지를 생성하지 않고 에러페이지를 보여준다. 하지만 많은 경우, 페이지를 빌드 할 당시에는 제한적인 숫자의 다이나믹 루트에 대해서만 Static build를 하고, 점차 증가되는 dynamic route에 대해서도 화면을 보여주고 싶을 수 있다. 또한 이때도 Incremental Static Regeneration을 하고 싶을 수있다.
이는 [여기]서 상세하게 나와있는데 요약하자면 아래와 같다.
If fallback is true, then the behavior of getStaticProps changes:
- The paths returned from getStaticPaths will be rendered to HTML at build time by getStaticProps.
- The paths that have not been generated at build time will not result in a 404 page. Instead, Next.js will serve a “fallback” version of the page on the first request to such a path (see “Fallback pages” below for details)
- In the background, Next.js will statically generate the requested path HTML and JSON. This includes running getStaticProps
- When that’s done, the browser receives the JSON for the generated path. This will be used to automatically render the page with the required props. From the user’s perspective, the page will be swapped from the fallback page to the full page.
- At the same time, Next.js adds this path to the list of pre-rendered pages. Subsequent requests to the same path will serve the generated page, just like other pages pre-rendered at build time.Fallback을 true로 설정하면 getStaticProps의 동작이 아래와 같이 변한다.
- fallback이 false일때와 동일하게 getStaticPaths에 정의된 route에 대해서는 빌드타임에 html을 생성한다
- 이때 생성되지 않은 경로에 접근할때 404페이지를 반환하는 것이 아니라, Next.js가 페이지의 fallback 버전을 우선 사용자에게 반환하고, 백그라운드에서 static하게 경로에 대해 html과 json을 생성하고, getStaticProps의 동작을 수행하고, 이가 완료 됬을때 JSON을 사용자에게 반환하다.
- 사용자는 Fallback 버전의 페이지에서 데이터가 채워넣어지는 경험을 한다.
- Next.js는 pre-rendered pages 목록에 이 경로를 포함시킨다. 그리고 이후의 요청은 마치 build타임에 생성되었던 것과 같이 동작한다.
이코드는 fallback을 true로 바꾸기만 한 코드이다
export const getStaticPaths: GetStaticPaths = async () => { console.log("getStaticPaths"); return { paths: [ { params: { username: "hayoung" } }, // See the "paths" section below ], fallback: true, // See the "fallback" section below }; }; // Incremental Static Site Regeneration export const getStaticProps: GetStaticProps = async ({ params }) => { const jsonData = await openJsonFile(); const username = params.username as string; const data: PostType[] = jsonData.contents[username] || []; return { props: { data, }, // will be passed to the page component as props revalidate: 1, }; };
아래 hayoung 경로에 대해서는 build 타임에 생성하고 incremental하게 변경하고, jiyeon 경로에 대해서는 요청하면 처음 생성한다음 그뒤로는 마치 hayoung 경로와 동일하게 동작하는 것을 보여준다.
실행화면
후기
이번달에 제대로 시작전에 프로젝트를 여러번 엎었었는데, 그때까지만해도 잘 이해가 안되던 것들이 지금 수차례 엎고나니까 조금 알것 같다는 생각도 든다!
'Web Dev > 5. Projects' 카테고리의 다른 글
[toy blog service] Webpack, TypeScript와 React(Babel은 천천히!) (0) 2021.04.14 [toy blog service] Preview Mode 이해하기 (0) 2021.04.13 [toy blog service] Intro Page와 Index 페이지를 통해서 살펴보는 Static Generation과 Incremental Static Regeneration차이 (0) 2021.04.13 [toy blog service] 각페이지를 어떻게 렌더링할지... + json으로 가짜 서버 만들기 (0) 2021.04.13 [toy blog service] Next.js의 Pages 이해하기(간단한 Typescript설정) (0) 2021.04.11