Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: get-server-side-props 번역 작업 #358

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
---
title: getServerSideProps
description: Fetch data on each request with `getServerSideProps`.
description: `getServerSideProps`를 사용하여 각 요청에 대한 데이터를 가져옵니다.
---

If you export a function called `getServerSideProps` (Server-Side Rendering) from a page, Next.js will pre-render this page on each request using the data returned by `getServerSideProps`.
페이지 내에서 `getServerSideProps`(서버-사이드 렌더링) 함수를 내보내면, Next.js는 `getServerSideProps` 의 반환 데이터를 사용하여 매 요청마다 해당 페이지를 사전 렌더링 합니다.

```tsx filename="pages/index.tsx" switcher
import type { InferGetServerSidePropsType, GetServerSideProps } from 'next'
Expand Down Expand Up @@ -40,42 +40,42 @@ 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에서 보여집니다. 이는 페이지가 올바르게 [hydrated](https://react.dev/reference/react-dom/hydrate)되도록 하기 위함입니다. `props`에 클라이언트에서 사용하면 안되는 민감한 정보를 전달하지 않도록 주의해야 합니다.

## When does getServerSideProps run
## getServerSideProps가 실행되는 시점

`getServerSideProps` only runs on server-side and never runs on the browser. If a page uses `getServerSideProps`, then:
`getServerSideProps`은 오직 서버-사이드에서만 실행되고 브라우저에서 절대 실행되지 않습니다. 만약 페이지 내에서 `getServerSideProps`를 사용할 경우.

- When you request this page directly, `getServerSideProps` runs at request time, and this page will be pre-rendered with the returned props
- When you request this page on client-side page transitions through [`next/link`](/docs/pages/api-reference/components/link) or [`next/router`](/docs/pages/api-reference/functions/use-router), Next.js sends an API request to the server, which runs `getServerSideProps`
- 페이지를 직접 요청하면 `getServerSideProps`는 요청 시점에 실행되고, 해당 페이지는 반환된 props와 함께 사전 렌더링 됩니다.
- [`next/link`](/docs/pages/api-reference/components/link) 혹은 [`next/router`](/docs/pages/api-reference/functions/use-router)를 사용해서 클라이언트 측 페이지 전환을 통해 페이지를 요청하면, Next.js는 `getServerSideProps`를 실행하는 API요청을 서버로 보냅니다.

`getServerSideProps` returns JSON which will be used to render the page. All this work will be handled automatically by Next.js, so you don’t need to do anything extra as long as you have `getServerSideProps` defined.
`getServerSideProps`는 페이지를 렌더링하는데 필요한 JSON을 반환합니다. 이 모든 작업은 Next.js에 의해 자동으로 처리됩니다. 따라서 `getServerSideProps`가 정의되어 있다면 추가적인 작업을 수행할 필요가 없습니다.

You can use the [next-code-elimination tool](https://next-code-elimination.vercel.app/) to verify what Next.js eliminates from the client-side bundle.
[next-code-elimination tool](https://next-code-elimination.vercel.app/)를 사용하면 Next.js가 클라이언트 측 번들에서 제거하는 내용을 확인할 수 있습니다.

`getServerSideProps` can only be exported from a **page**. You can’t export it from non-page files.
`getServerSideProps`는 오직 **페이지**에서만 내보낼 수 있습니다. page가 아닌 파일에서는 내보낼 수 없습니다.

Note that you must export `getServerSideProps` as a standalone function — it will **not** work if you add `getServerSideProps` as a property of the page component.
`getServerSideProps`는 독립적인 함수로 내보내야 합니다 - 페이지 컴포넌트의 속성으로 `getServerSideProps`를 추가할 경우 동작하지 않습니다.

The [`getServerSideProps` API reference](/docs/pages/api-reference/functions/get-server-side-props) covers all parameters and props that can be used with `getServerSideProps`.
[`getServerSideProps` API 레퍼런스](/docs/pages/api-reference/functions/get-server-side-props)는 `getServerSideProps`와 함께 사용할 수 있는 모든 매개변수와 props에 대해 설명합니다.

## When should I use getServerSideProps
## getServerSideProps를 사용해야 하는 경우

You should use `getServerSideProps` only if you need to render a page whose data must be fetched at request time. This could be due to the nature of the data or properties of the request (such as `authorization` headers or geo location). Pages using `getServerSideProps` will be server side rendered at request time and only be cached if [cache-control headers are configured](/docs/pages/building-your-application/deploying/production-checklist#caching).
요청 시 데이터를 가져오는 페이지 렌더링을 할 때 `getServerSideProps`를 사용해야 합니다. 이는 데이터 특성 또는 요청의 속성 (`authorization` 헤더 혹은 지리적 위치)이 이유가 될 수 있습니다. `getServerSideProps`를 사용하는 페이지는 요청시 서버 측에서 렌더링되며 [캐시-제어 헤더가 구성되어 있을 경우](/docs/pages/building-your-application/deploying/production-checklist#caching)에만 캐시됩니다.

If you do not need to render the data during the request, then you should consider fetching data on the [client side](#fetching-data-on-the-client-side) or [`getStaticProps`](/docs/pages/building-your-application/data-fetching/get-static-props).
요청 중에 데이터 렌더링할 필요가 없는 경우, [클라이언트 측](#fetching-data-on-the-client-side)에서 데이터를 가져오거나 [`getStaticProps`](/docs/pages/building-your-application/data-fetching/get-static-props)를 고려해야합니다.

### getServerSideProps or API Routes
### getServerSideProps 또는 API 라우트

It can be tempting to reach for an [API Route](/docs/pages/building-your-application/routing/api-routes) when you want to fetch data from the server, then call that API route from `getServerSideProps`. This is an unnecessary and inefficient approach, as it will cause an extra request to be made due to both `getServerSideProps` and API Routes running on the server.
`getServerSideProps`에서 서버로부터 데이터를 가져오기 위해 [API 라우트](/docs/pages/building-your-application/routing/api-routes)를 사용하려는 유혹이 있을 수 있습니다. 이는 불필요하고 비효율적인 접근 방식입니다. 왜냐하면 `getServerSideProps`와 API 라우트 둘 다 서버에서 실행되므로 추가 요청이 발생하기 때문입니다.

Take the following example. An API route is used to fetch some data from a CMS. That API route is then called directly from `getServerSideProps`. This produces an additional call, reducing performance. Instead, directly import the logic used inside your API Route into `getServerSideProps`. This could mean calling a CMS, database, or other API directly from inside `getServerSideProps`.
다음 예를 들어보겠습니다. CMS에서 데이터를 가져오기 위해 API 라우트를 사용하고, 이 API 라우트를 `getServerSideProps`에서 직접 호출합니다. 이렇게 하면 성능이 저하되는 추가적인 호출이 발생합니다. 대신, API 라우트 내부에서 사용되는 로직을 `getServerSideProps`에서 직접 가져오는 것이 좋습니다. 이는 `getServerSideProps` 내부에서 CMS, 데이터베이스 또는 다른 API를 직접 호출하는 것을 의미합니다.

### getServerSideProps with Edge API Routes
### getServerSideProps를 Edge API 라우트와 함께 사용하는 경우

`getServerSideProps` can be used with both [Serverless and Edge Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes), and you can set props in both. However, currently in the Edge Runtime, you do not have access to the response object. This means that you cannot — for example — add cookies in `getServerSideProps`. To have access to the response object, you should **continue to use the Node.js runtime**, which is the default runtime.
`getServerSideProps`[Serverless Edge Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes)과 함께 사용할 수 있으며 양쪽에서 모두 props를 설정할 수 있습니다. 하지만, 현재 'Edge 런타임'에서는 응답 객체에 접근할 수 없습니다. 즉 - 예를 들어 - `getServerSideProps`에서 쿠키를 추가할 수 없습니다. 응답 객체에 접근하려면, 기본적으로 사용되는 **Node.js 런타임을 계속 사용해야 합니다.**
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

해당 부분에 Edge RuntimesEdge 런타임이 함께 쓰여있는데 복수와 단수의 차이로 따로 사용해주신게 맞으신가요?
본문에 없는 따옴표는 제거해주셔도 될 것 같습니다! -> 'Edge 런타임'


You can explicitly set the runtime on a per-page basis by modifying the `config`, for example:
`config`를 수정하여 각 페이지마다 명시적으로 런타임을 설정할 수 있습니다. 아래는 예시 코드입니다.

```jsx filename="pages/index.js"
export const config = {
Expand All @@ -85,49 +85,50 @@ export const config = {
export const getServerSideProps = async () => {}
```

## Fetching data on the client side
## 클라이언트 측에서 데이터 가져오기

If your page contains frequently updating data, and you don’t need to pre-render the data, you can fetch the data on the [client side](/docs/pages/building-your-application/data-fetching/client-side). An example of this is user-specific data:
만약 페이지에 자주 업데이트되는 데이터가 포함되어 있고 데이터를 사전 렌더링 할 필요가 없다면, 헤당 데이터를 [클라이언트 측](/docs/pages/building-your-application/data-fetching/client-side)에서 가져올 수 있습니다. 아래는 사용자 별 데이터 예시입니다.

- First, immediately show the page without data. Parts of the page can be pre-rendered using Static Generation. You can show loading states for missing data
- Then, fetch the data on the client side and display it when ready
- 먼저, 데이터가 없는 상태에서 즉시 페이지를 표시합니다. 페이지의 일부는 정적 생성(Static Generation)을 사용하여 사전 렌더링 할 수 있습니다. 누락된 데이터는 로딩 상태로 표시할 수 있습니다.
- 그 후에, 클라이언트 측에서 데이터를 가져와 준비가 되면 해당 데이터를 표시합니다.

This approach works well for user dashboard pages, for example. Because a dashboard is a private, user-specific page, SEO is not relevant and the page doesn’t need to be pre-rendered. The data is frequently updated, which requires request-time data fetching.
이 접근 방식은 사용자 대시보드 페이지와 같은 경우에 잘 적용해 볼 수 있습니다. 대시보드는 비공개이고 사용자 별 페이지이므로 SEO가 관련이 없고 해당 페이지는 사전 렌더링 할 필요가 없습니다. 데이터가 자주 없데이트 되기 때문에, 요청 시간에 데이터를 가져와야 합니다.

## Using getServerSideProps to fetch data at request time
## getServerSideProps를 사용하여 요청 시 데이터 가져오기

The following example shows how to fetch data at request time and pre-render the result.
다음 예시는 요청 시 데이터를 가져오고 결과를 사전 렌더링하는 방법을 보여 줍니다.

```jsx
function Page({ data }) {
// Render data...
// 데이터 렌더링...
}

// This gets called on every request
// 이 함수는 매 요청마다 호출됩니다
export async function getServerSideProps() {
// Fetch data from external API
// 외부 API에서 데이터 가져옵니다.
const res = await fetch(`https://.../data`)
const data = await res.json()

// Pass data to the page via props
// props를 통해 데이터를 페이지로 전달합니다.
return { props: { data } }
}

export default Page
```

## Caching with Server-Side Rendering (SSR)
## Server-Side Rendering (SSR)을 사용한 캐싱

You can use caching headers (`Cache-Control`) inside `getServerSideProps` to cache dynamic responses. For example, using [`stale-while-revalidate`](https://web.dev/stale-while-revalidate/).
`getServerSideProps`안에서 캐시 헤더(`Cache-Control`)를 사용하여 동적 응답을 캐시할 수 있습니다. 예를 들면, [`stale-while-revalidate`](https://web.dev/stale-while-revalidate/)를 사용할 수 있습니다.

```jsx
// This value is considered fresh for ten seconds (s-maxage=10).
// If a request is repeated within the next 10 seconds, the previously
// cached value will still be fresh. If the request is repeated before 59 seconds,
// the cached value will be stale but still render (stale-while-revalidate=59).
// 이 값은 10초 동안 새로운 값으로 간주됩니다. (s-maxage=10)
// 다음 10초 내에 동일한 요청이 반복되면, 이전의
// 캐시된 값은 여전히 새로운 값으로 간주됩니다. 동일한 요청이 59초 이내에 반복된다면,
// 캐시된 값은 오래되었지만 렌더링은 여전히 유지되고 있을 것입니다.(stale-while-revalidate=59).
//
// In the background, a revalidation request will be made to populate the cache
// with a fresh value. If you refresh the page, you will see the new value.
// 백그라운드에서, 캐시를 새로운 값으로 채우기 위해 재검증(revalidation) 요청이 수행됩니다.
// 페이지를 새로고침하면, 새로운 값이 표시됩니다.

export async function getServerSideProps({ req, res }) {
res.setHeader(
'Cache-Control',
Expand All @@ -140,8 +141,9 @@ export async function getServerSideProps({ req, res }) {
}
```

Learn more about [caching](/docs/pages/building-your-application/deploying/production-checklist#caching).
자세한 내용은 [캐싱](/docs/pages/building-your-application/deploying/production-checklist#caching)을 참조하세요.

## Does getServerSideProps render an error page
## getServerSideProps가 오류 페이지를 렌더링하는 경우

If an error is thrown inside `getServerSideProps`, it will show the `pages/500.js` file. Check out the documentation for [500 page](/docs/pages/building-your-application/routing/custom-error#500-page) to learn more on how to create it. During development this file will not be used and the dev overlay will be shown instead.
`getServerSideProps` 함수 내에서 오류가 발생하면, `pages/500.js` 파일을 표시합니다. [500 page](/docs/pages/building-your-application/routing/custom-error#500-page)에 대한 문서를 확인하여 해당 페이지를 생성하는 방법에 대해 자세히 알아보세요.
개발 중에는 해당 파일이 사용되지 않고 개발용 오버레이(dev overlay)가 대신 표시됩니다.