Next.js의 Pages

Soly; 독특하게·2021년 2월 23일
1

Next.js

목록 보기
3/3
post-thumbnail

Pre-rendering

Next.js에서는 모든 페이지를 'Pre-rendering'한다.

이는, Client의 JavaScript에서 모든 작업을 수행하는 대신, 각 페이지에 대해 미리 HTML을 생성한다.

그렇기 때문에 SEO가 가능하다.

SEO(Search engine optimization; 검색엔진 최적화)

  • Hydration 과정?

각 HTML 페이지는 최소한의 JavaScript 코드와 연결 한다.

즉, 브라우저에서 페이지를 로드하면, 해당 JavaScript코드가 실행되고 완전히 interactive하게 됩니다.

인터랙티브한 웹페이지 예시

Static Generation

장점 : 서버가 모든 요청에 페이지를 렌더링 하는 것보다 빠르다.

→ 페이지를 한 번 빌드하고 CDN에서 제공할 수 있다면 static Generation을 사용하는 것이 좋다.

BUT! 사용자의 요청 전에 페이지를 미리 렌더링 할 수없다면 피해야 한다.

Static Generation을 할 수 없는 경우
1. Client-side Rendering : 일부를 건너뛰고 js로 채울 수 있다
2. Server-Side Rendering : 각 요청 페이지를 미리 렌더링 한다.
CDN에서는 페이지를 캐시 할 수 없어 속도가 느리지만 사전 렌더링 된 페이지는 항상 최신버전이다.

Server-Side Rendering (SSR)

페이지 HTML은 각 요청에 대해 생성 된다.

모든 요청에서 서버에 호출되는 getServerSideProps함수에서 async로 데이터를 가져오고, 함수를 export한다.

function Page({ data }) {
  // Render data...
}

// This gets called on every request
export async function getServerSideProps() {
  // Fetch data from external API
  const res = await fetch(`https://.../data`)
  const data = await res.json()

  // Pass data to the page via props
  return { props: { data } }
}

export default Page

getServerSideProps VS getStaticProps

  • getServerSideProps빌드 시간이 아닌 모든 요청에서 실행된다.

Static Generation without data

기본적으로 Next.js는 데이터를 가져오지 않고 정적 생성으로 페이지를 사전 렌더링 한다.

사전 렌더링 할 때, 외부 데이터를 가져올 필요가 없다면 빌드시간동안 단일 HTML 파일을 생성한다.

Static Generation with data

데이터가 존재하기 때문에, 사전 렌더링을 위해 외부데이터를 가져와야 한다.

  • 콘텐츠가 외부 데이터에 따라 다를 경우 : getStaticProps
  • 경로가 외부데이터에 따라 다를 경우 : getStaticPaths (+ 추가할 경우 getStaticProps)

1. 페이지의 내용이 외부 데이터에 의존하는 경우

사전 렌더링에서 데이터를 가져오기 위해서 getStaticProps 함수를 사용해 async/await 로 데이터를 가져오고 export할 수 있도록 한다.

빌드시 반드시 호출되고 props로 사전 렌더링 시 가져온 데이터를 페이지의 페이지로 전달 할 수 있다.

function Blog({ posts }) {
  // Render posts...
}

// This function gets called at build time
export async function getStaticProps() {
  // Call an external API endpoint to get posts
  const res = await ****fetch('https://.../posts')
  const posts = await res.json()

  // By returning { props: { posts } }, the Blog component
  // will receive `posts` as a prop at build time
  return {
    props: {
      posts,
    },
  }
}

export default Blog

2. 페이지 경로가 외부데이터에 의존하는 경우

경로가 동적인 페이지를 만들 수 있다.

EX) pages/posts/[id].js 로 기반을 잡으면,

id : 1 일 경우에 post/1로 경로가 표시된다. id : 2 일 경우에 post/2 ...

즉, id값에 따라서 경로가 바뀐다.

때문에, 사전 렌더링 된 페이지의 경로는 외부데이터에 따라 달라진다. 이 경우, 빌드시 호출할 수 있고 사전 렌더링 할 경로를 지정하는 getStaticPaths 함수를 사용한다. 마찬가지로 async/await 로 데이터를 가져오고 export할 수 있도록 한다.

// This function gets called at build time
export async function getStaticPaths() {
  // Call an external API endpoint to get posts
  const res = await fetch('https://.../posts')
  const posts = await res.json()

  // Get the paths we want to pre-render based on posts
  const paths = posts.map((post) => `/posts/${post.id}`)

  // We'll pre-render only these paths at build time.
  // { fallback: false } means other routes should 404.
  return { paths, fallback: false }
}

더불어, getStaticProps 로 경로에 따른 내용에 대한 데이터를 가져올 수 있도록 한다.

function Post({ post }) {
  // Render post...
}

export async function getStaticPaths() {
  // ...
}

// This also gets called at build time
export async function getStaticProps({ params }) {
  // params contains the post `id`.
  // If the route is like /posts/1, then params.id is 1
  const res = await fetch(`https://.../posts/${params.id}`)
  const post = await res.json()

  // Pass post data to the page via props
  return { props: { post } }
}

export default Post
profile
협업을 즐겨하는 목표지향적인, Front-End 개발자입니다.

0개의 댓글