next-js [ssr, ssg]

gak·2023년 3월 29일
0

Pre-rendering

Pre-rendering 은 Next js 에서 기본적으로 Html 파일을 생성한 뒤 클라이언트에 보내주는 것이다. 이 기능은 default 로 작동한다.

Hydration

Pre-rendering 된 HTML 파일과 js 번들을 클라이언트가 받으면, HTML 에 js 를 실행시켜, 이벤트를 붙이거나 추가적인 UI 를 렌더링한다. 이 과정을 hydration 이라고 부른다. HTML 파일에 js 를 적셔서 완성본을 만든다는 의미에서 Hydration 이란 용어를 쓴건가?!

Pre-rendering (2종류)

차이점은, HTML 파일이 언제 생기느냐이다.
1. Static Site Generation(SSG) : HTML 파일이 빌드타임에 생성된다.
2. Server-side Rendering(SSR) : Request 마다 HTML 파일이 생성된다.

두 방법을 비교하면, 당연하게도 성능상으로 Static Generation 이 더 뛰어나다. 더욱이 Static Generation 은 CDN 에 자동으로 캐시된다!!

SSG With Data

1) Static Generation 의 컨텐츠 렌더링과정에서 외부의 데이터가 필요한 경우가 있다.

export default function Blog({ posts }) {
  return (
    <ul>
      {posts.map((post) => (
        <li>{post.title}</li>
      ))}
    </ul>
  )
}

/blog 라는 url 에 해당하는 HTML 을 만들기 위해서는 posts 가 필요하다.
이때 nextjs 에서 제공하는 getStaticProps 라는 비동기 함수를 사용하여 props 를 만들어주면 Blog 컴포넌트를 Static Generation 을 사용해 HTML 로 만들 수 있다.

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,
    },
  }
}

이렇게 되면, 빌드타임에 해당 api 로 요청을 보내 Posts 를 가져와서 Post 라는 컴포넌트의 HTML 파일을 만든다.

2) 어떤 페이지를 렌더링할지가 외부의 데이터에 의해서 정해지는 경우
가령.. pages/post/[id].tsx 의 경우에..
id가 몇인 페이지를 Pre-rendering 할지 정해야한다.

이때 next 에서 제공하는 getStaticPaths 라는 비동기 함수를 사용할 수 있다.

// 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) => ({
    params: { id: post.id },
  }))

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

대부분 getStaticPaths 는 getStaticProps 와 함께 사용되며,
해당 path 에 해당하는 데이터를 fetch 해서 Pre-rendering 할 수 있다.

export default 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 } }
}

SSR with Data

ssr 과 static generation 의 차이는, 데이터를 언제 불러오느냐이다.
ssr 은 클라이언트의 request 가 발생하면 데이터를 불러와 HTML 을 만든 뒤 전송하고, static generation 은 빌드타임에 데이터를 불러와 미리 HTML 을 만든다.

ssr 에서 data 를 fetching 하기 위해서는
getServerSideProps 라는 비동기 함수를 사용해야한다.

export default 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 } }
}
profile
Hello. I'm Front-End Developer Trying to Create Valuable Things.

0개의 댓글