Skip to content

Commit

Permalink
[#26] docs: get-static-props 번역 (#49)
Browse files Browse the repository at this point in the history
* [#26] docs: get-static-props 번역

* [#26] docs: get-static-props hydrated -> hydrate로 변경
  • Loading branch information
f0rever0 committed Jul 31, 2024
1 parent 5e5eeac commit d4d253a
Showing 1 changed file with 47 additions and 80 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,9 @@ title: getStaticProps
description: Fetch data and generate static pages with `getStaticProps`. Learn more about this API for data fetching in Next.js.
---

{/* TODO: 번역이 필요합니다. */}

# getStaticProps

If you export a function called `getStaticProps` (Static Site Generation) from a page, Next.js will pre-render this page at build time using the props returned by `getStaticProps`.
페이지에서 `getStaticProps`(정적 사이트 생성) 라는 함수를 내보낸다면, Next.js는 `getStaticProps`로부터 반환된 props를 사용하여 이 페이지를 빌드 타임에 미리 렌더링을 합니다.

```tsx filename="pages/index.tsx" switcher
import type { InferGetStaticPropsType, GetStaticProps } from 'next'
Expand Down Expand Up @@ -44,70 +42,39 @@ export default function Page({ repo }) {
}
```

> Note that irrespective of rendering type, any `props` will be passed to the page component and can be viewed on the client-side in the initial HTML. This is to allow the page to be [hydrated](https://react.dev/reference/react-dom/hydrate) correctly. Make sure that you don't pass any sensitive information that shouldn't be available on the client in `props`.
> 렌더링 타입과 무관하게, 모든 props는 페이지 컴포넌트로 전달되며 초기 HTML 클라이언트 사이드에서 볼 수 있다는 것을 주의하세요. 이것은 [hydrate](https://react.dev/reference/react-dom/hydrate)가 제대로 실행되기 위함입니다. 클라이언트에서 사용하면 안되는 어떠한 민감한 정보도 props에 전달해서는 안됩니다.
The [`getStaticProps` API reference](/docs/pages/api-reference/functions/get-static-props) covers all parameters and props that can be used with `getStaticProps`.
[`getStaticProps` API reference](/docs/pages/api-reference/functions/get-static-props) `getStaticProps`에서 사용할 수 있는 모든 파라미터와 props를 포함합니다.

## When should I use getStaticProps?

You should use `getStaticProps` if:
다음과 같은 상황에서 `getStaticProps` 를 사용할 수 있습니다.

- The data required to render the page is available at build time ahead of a user’s request
- The data comes from a headless CMS
- The page must be pre-rendered (for SEO) and be very fast — `getStaticProps` generates `HTML` and `JSON` files, both of which can be cached by a CDN for performance
- The data can be publicly cached (not user-specific). This condition can be bypassed in certain specific situation by using a Middleware to rewrite the path.
- 페이지 렌더링에 필요한 데이터가 유저의 요청 이전인 빌드 타임에 사용 가능해야 할 때
- 데이터가 headless CMS 으로부터 제공될 때
- 페이지가 SEO를 위해서 반드시 미리 렌더링 되어야 하고 매우 빨라야 할 때 - getStaticProps는 `HTML``JSON` 파일을 생성합니다. 두 가지 모두 성능을 위해 CDN에 캐시를 저장합니다.
- 데이터는 개별 사용자 별로가 아니라 공개적으로 캐시되어야 할 때. 이 조건은 경로를 재설정하기 위해 미들웨어를 사용하는 방식으로 특정 상황에서 우회될 수 있습니다.

## When does getStaticProps run

`getStaticProps` always runs on the server and never on the client. You can validate code written inside `getStaticProps` is removed from the client-side bundle [with this tool](https://next-code-elimination.vercel.app/).
`getStaticProps` 항상 서버에서 실행되며 클라이언트에서는 실행되지 않습니다. [이 도구](https://next-code-elimination.vercel.app/)를 사용하여 클라이언트 bundle에서 제거된 `getStaticProps` 내부에 작성된 코드를 검증할 수 있습니다.

- `getStaticProps` always runs during `next build`
- `getStaticProps` runs in the background when using [`fallback: true`](/docs/pages/api-reference/functions/get-static-paths#fallback-true)
- `getStaticProps` is called before initial render when using [`fallback: blocking`](/docs/pages/api-reference/functions/get-static-paths#fallback-blocking)
- `getStaticProps` runs in the background when using `revalidate`
- `getStaticProps` runs on-demand in the background when using [`revalidate()`](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration#on-demand-revalidation)
- `getStaticProps` 는 항상 next build 중 실행됩니다.
- `getStaticProps` [`fallback: true`](/docs/pages/api-reference/functions/get-static-paths#fallback-true)를 사용할때 백그라운드에서 실행됩니다.
- `getStaticProps` [`fallback: blocking`](/docs/pages/api-reference/functions/get-static-paths#fallback-blocking)을 사용할때 초기 렌더링 이전에 호출됩니다.
- `getStaticProps` `revalidate`를 사용할때 백그라운드에서 실행됩니다.
- `getStaticProps` [`revalidate()`](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration#on-demand-revalidation)를 사용할때 수요에 따라 백그라운드에서 실행됩니다.

When combined with [Incremental Static Regeneration](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration), `getStaticProps` will run in the background while the stale page is being revalidated, and the fresh page served to the browser.
[Incremental Static Regeneration](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration)와 결합할 때, `getStaticProps`는 오래된 페이지가 재검증 되는 동안 백그라운드에서 실행될 수 있으며 브라우저에서 새 페이지가 제공됩니다.

`getStaticProps` does not have access to the incoming request (such as query parameters or HTTP headers) as it generates static HTML. If you need access to the request for your page, consider using [Middleware](/docs/pages/building-your-application/routing/middleware) in addition to `getStaticProps`.
`getStaticProps`는 정적 HTML을 생성하기 때문에, 쿼리 파라미터 또는 HTTP 헤더와 같이 들어오는 요청에 접근할 수 없습니다. 만약 페이지를 위한 요청에 접근하고 싶다면, `getStaticProps`[미들웨어](/docs/pages/building-your-application/routing/middleware) 를 함께 사용하는 것을 고려해야합니다.

## Using getStaticProps to fetch data from a CMS

The following example shows how you can fetch a list of blog posts from a CMS.
다음 예제는 CMS로부터 어떻게 blog posts 리스트를 가져오는지 보여줍니다.

```tsx filename="pages/blog.tsx" switcher
// posts will be populated at build time by getStaticProps()
export default function Blog({ posts }) {
return (
<ul>
{posts.map((post) => (
<li>{post.title}</li>
))}
</ul>
)
}

// This function gets called at build time on server-side.
// It won't be called on client-side, so you can even do
// direct database queries.
export async function getStaticProps() {
// Call an external API endpoint to get posts.
// You can use any data fetching library
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,
},
}
}
```

```jsx filename="pages/blog.js" switcher
// posts will be populated at build time by getStaticProps()
// posts는 getStaticProps()에 의해 빌드 타임에 생성됩니다.
export default function Blog({ posts }) {
return (
<ul>
Expand All @@ -118,17 +85,17 @@ export default function Blog({ posts }) {
)
}

// This function gets called at build time on server-side.
// It won't be called on client-side, so you can even do
// direct database queries.
// 이 함수는 서버 사이드 빌드 타임에 호출됩니다.
// 클라이언트 사이드에서는 호출되지 않습니다. 따라서
// 직접 데이터베이스 쿼리를 수행할 수도 있습니다.
export async function getStaticProps() {
// Call an external API endpoint to get posts.
// You can use any data fetching library
// posts를 얻기 위해서 외부 API endpoint를 호출합니다.
// 모든 fetching library 를 사용할 수 있습니다.
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
// { props: { posts } }를 반환함으로써
// Blog 컴포넌트는 빌드타임에 posts를 props로 받습니다.
return {
props: {
posts,
Expand All @@ -137,20 +104,20 @@ export async function getStaticProps() {
}
```

The [`getStaticProps` API reference](/docs/pages/api-reference/functions/get-static-props) covers all parameters and props that can be used with `getStaticProps`.
[`getStaticProps` API reference](/docs/pages/api-reference/functions/get-static-props)`getStaticProps`에서 사용할 수 있는 모든 파라미터와 props를 포함합니다.

## Write server-side code directly

As `getStaticProps` runs only on the server-side, it will never run on the client-side. It won’t even be included in the JS bundle for the browser, so you can write direct database queries without them being sent to browsers.
`getStaticProps`는 서버 사이드에서만 실행되고 클라이언트 사이드에서는 절대로 실행되지 않습니다. 브라우저용 JS 번들에 포함되지 않기 때문에 이를 브라우저에 보내지 않고 직접 데이터베이스 쿼리를 작성할 수 있습니다.

This means that instead of fetching an **API route** from `getStaticProps` (that itself fetches data from an external source), you can write the server-side code directly in `getStaticProps`.
이것은 `getStaticProps` 로 부터 **API 라우트**를 가져오는 대신 외부 소스로부터 데이터를 가져오는 `getStaticProps` 에서 직접 서버 사이드 코드를 작성할 수 있다는 것을 의미합니다.

Take the following example. An API route is used to fetch some data from a CMS. That API route is then called directly from `getStaticProps`. This produces an additional call, reducing performance. Instead, the logic for fetching the data from the CMS can be shared by using a `lib/` directory. Then it can be shared with `getStaticProps`.
다음 예제를 살펴보면 API 라우트는 CMS로부터 데이터를 가져오기 위해 사용됩니다. 해당 API 라우트는 `getStaticProps` 에서 직접 호출됩니다. 이렇게 하면 추가적인 호출이 발생하여 성능이 저하됩니다. 대신 CMS에서 데이터를 가져오는 로직을 `lib/` 폴더를 사용하여 공유할 수 있습니다. 그리고 이것은 `getStaticProps`와 함께 공유할 수 있습니다.

```js filename="lib/load-posts.js"
// The following function is shared
// with getStaticProps and API routes
// from a `lib/` directory
// 이 함수는
// getStaticProps API 라우트와 함께
// `lib/` 폴더 에서 공유됩니다.
export async function loadPosts() {
// Call an external API endpoint to get posts
const res = await fetch('https://.../posts/')
Expand All @@ -164,43 +131,43 @@ export async function loadPosts() {
// pages/blog.js
import { loadPosts } from '../lib/load-posts'

// This function runs only on the server side
// 이 함수는 서버 사이드에서만 실행됩니다.
export async function getStaticProps() {
// Instead of fetching your `/api` route you can call the same
// function directly in `getStaticProps`
// `/api` 라우트에서 가져오는 대신에
// 동일한 함수를 `getStaticProps`안에서 직접 호출할 수 있습니다.
const posts = await loadPosts()

// Props returned will be passed to the page component
// 반환된 props는 page 컴포넌트로 전달됩니다.
return { props: { posts } }
}
```

Alternatively, if you are **not** using API routes to fetch data, then the [`fetch()`](https://developer.mozilla.org/docs/Web/API/Fetch_API) API _can_ be used directly in `getStaticProps` to fetch data.
또는, 데이터를 가져오기 위해 API 라우트를 사용하지 **않을경우**, [`fetch()`](https://developer.mozilla.org/docs/Web/API/Fetch_API) API 는 데이터를 가져오기 위해 `getStaticProps`안에서 직접 사용될 수 있습니다.

To verify what Next.js eliminates from the client-side bundle, you can use the [next-code-elimination tool](https://next-code-elimination.vercel.app/).
클라이언트 사이드 bundle에서 Next.js가 무엇을 제거하는지 확인하기 위해서, [next-code-elimination tool](https://next-code-elimination.vercel.app/)를 사용할 수 있습니다.

## Statically generates both HTML and JSON

When a page with `getStaticProps` is pre-rendered at build time, in addition to the page HTML file, Next.js generates a JSON file holding the result of running `getStaticProps`.
`getStaticProps`를 사용하는 페이지가 빌드 타임에서 미리 렌더링 될 때, HTML 파일을 추가하기 위해서, Next.js는 `getStaticProps`를 실행한 결과를 담은 JSON 파일을 생성합니다.

This JSON file will be used in client-side routing through [`next/link`](/docs/pages/api-reference/components/link) or [`next/router`](/docs/pages/api-reference/functions/use-router). When you navigate to a page that’s pre-rendered using `getStaticProps`, Next.js fetches this JSON file (pre-computed at build time) and uses it as the props for the page component. This means that client-side page transitions will **not** call `getStaticProps` as only the exported JSON is used.
JSON 파일은 [`next/link`](https://github.com/luciancah/nextjs-ko/blob/main/docs/pages/api-reference/components/link) 나 [`next/router`](https://github.com/luciancah/nextjs-ko/blob/main/docs/pages/api-reference/functions/use-router) 를 통해 클라이언트 사이드에서 사용될 수 있습니다. `getStaticProps`를 사용하여 미리 렌더링된 페이지로 이동할때, Next.js는 빌드 타임에 미리 계산된 JSON 파일을 가져옵니다. 이것은 클라이언드 사이드 페이지 전환은 내보낸 JSON만 사용하므로 `getStaticProps`를 호출하지 **않는다**는 것을 의미합니다.

When using Incremental Static Generation, `getStaticProps` will be executed in the background to generate the JSON needed for client-side navigation. You may see this in the form of multiple requests being made for the same page, however, this is intended and has no impact on end-user performance.
Incremental Static Generation를 사용할때, 클라이언트 사이드 이동에 필요한 JSON을 생성하기 위해 `getStaticProps` 가 백그라운드에서 실행됩니다. 동일한 페이지에 대한 요청이 여러번 이루어지는 것으로 볼 수도 있지만, 이것은 의도된 것이며 최종 사용자 성능에는 영향을 미치지 않습니다.

## Where can I use getStaticProps

`getStaticProps` can only be exported from a **page**. You **cannot** export it from non-page files, `_app`, `_document`, or `_error`.
`getStaticProps` 은 오직 **페이지**에서 export 되어야 합니다. 페이지가 아닌 파일, `_app`, `_document`, 또는 `_error`. 에서는 export 할 수 **없습니다**.

One of the reasons for this restriction is that React needs to have all the required data before the page is rendered.
이러한 제약의 이유 중 하나는 React는 페이지가 렌더링되기 전에 필요한 모든 데이터를 가지기를 원하기 때문입니다.

Also, you must use export `getStaticProps` as a standalone function — it will **not** work if you add `getStaticProps` as a property of the page component.
또한, `getStaticProps`는 독립 함수으로써 내보내야합니다. - 만약 `getStaticProps`를 페이지 컴포넌트의 속성으로 추가한다면 작동하지 않습니다.

> **Good to know**: if you have created a [custom app](/docs/pages/building-your-application/routing/custom-app), ensure you are passing the `pageProps` to the page component as shown in the linked document, otherwise the props will be empty.
> **알아두면 좋은 점**: 만약 [custom app](/docs/pages/building-your-application/routing/custom-app) 를 생성한다면, 연결된 문서에 나와있는 것처럼 페이지 컴포넌트로 `pageProps` 를 전달하세요. 그렇지 않으면 props는 비어있을 것입니다.
## Runs on every request in development

In development (`next dev`), `getStaticProps` will be called on every request.
개발 환경(`next dev`)에서, `getStaticProps`는 각 요청마다 호출됩니다.

## Preview Mode

You can temporarily bypass static generation and render the page at **request time** instead of build time using [**Preview Mode**](/docs/pages/building-your-application/configuring/preview-mode). For example, you might be using a headless CMS and want to preview drafts before they're published.
[**미리보기 모드**](/docs/pages/building-your-application/configuring/preview-mode)를 사용하여 일시적으로 정적 생성을 우회하고 빌드 타임 대신 **요청 타임**에 페이지를 렌더링할 수 있습니다. 예를 들어 headless CMS 를 사용 중이거나 출시되기 이전에 초안을 미리 보고싶을 때 해당 모드를 사용할 수 있습니다.

0 comments on commit d4d253a

Please sign in to comment.