> For the complete documentation index, see [llms.txt](https://tech.x2bee.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://tech.x2bee.com/dev-guide/pjt-prepare/publish-your-docs/store-front-framewok-next.js/04.-data-fetching/3.-next.js-restapi.md).

# 3. Next.js용 공통 유틸 RestApi 사용

이 문서는 Next.js용 RestApi를 사용하여 데이터를 가져오는 방법에 대한 안내입니다.

Next.js에서는 Server component, Client component에 따라 restApiUtil의 사용법이 조금씩 달라집니다. 또한 Next.js 내에서 반복적으로 수행하는 공통 기능 등을 추가한 next(react)에 맞춰서 만들어진 RestApi Util을 제공합니다.

* 둘다 사이트(비즈니스 로직)에 맞춰서 공통화된 기능이 들어가 있음. (쿠키값에서 token을 가져와 추가 등)
* Server component의 내부적으로 Server Action 기능을 사용함
* Client component의 경우 내부적으로 React Hook 기능을 사용함

{% stepper %}
{% step %}

### Server Component

Server Component는 Promise를 반환하므로 then/catch 패턴이나 async/await 문법을 사용하여 처리합니다. 아래 예시는 async/await를 사용한 예입니다.

{% code title="app/page.tsx (Server Component 예시)" %}

```javascript
import { restApi } from '@/lib/common/plugins/restApi';

const Home = async () => {
  const response = await restApi.get('/api/display/v1/shop/1?dispMediaCd=20');
  console.log(response);

  return (
    <div>
      <h1>Home</h1>
    </div>
  );
};

export default Home;
```

{% endcode %}

Server Component에서는 내부적으로 Server Action 기능을 사용하도록 구현되어 있습니다.
{% endstep %}

{% step %}

### Client Component

Client Component에서는 React Hook을 사용하여 데이터를 가져옵니다. useEffect 내부나 이벤트 핸들러에서 async 함수를 호출하는 방식이 일반적입니다.

{% code title="app/page.tsx (Client Component 예시)" %}

```javascript
'use client';
import { useEffect } from 'react';
import { restApi } from '@/lib/common/plugins/restApi';

const Home = () => {
  useEffect(() => {
    const apiFunc = async () => {
      const response = await restApi.get('/api/display/v1/shop/1?dispMediaCd=20');
      console.log(response);
    };
    apiFunc();
  }, []);

  async function apitest() {
    const response = await restApi.get('/api/display/v1/shop/1?dispMediaCd=20');
    console.log(response);
  }

  return (
    <div>
      <h1>Home</h1>
      <button onClick={() => apitest()}>api test</button>
    </div>
  );
};

export default Home;
```

{% endcode %}

Client Component는 내부적으로 React Hook 기반 구현을 사용합니다.
{% endstep %}

{% step %}

### x2bee 표준 및 관리를 위한 api 작성 방법

<div align="left"><figure><img src="/files/Jqg59a5Vp16ZJmxQW2kN" alt="" width="347"><figcaption></figcaption></figure></div>

화면마다 개별적으로 API를 작성하기보다, 프로젝트 내에 api 디렉토리를 만들어 업무 또는 API별 파일로 분리해 작성하는 것을 권장합니다. 이렇게 하면 중복 코드를 줄이고 관련 API를 함께 관리하여 통일성을 유지하기 좋습니다.

예시:

{% code title="src/api/categoryApi.ts" %}

```javascript
import { restApi } from '@/lib/common/plugins/restApi';
import { DisplayCategory } from '@/types/display/category-data-model';
import { ResponseEntity } from '@/lib/common/plugins/restApi/restApiModel';

const CategoryApi = async (params?: { brandNo: string }) => {
  const response: ResponseEntity = (await restApi.get(
    '/api/display/v1/displayCategory',
    { params }
  )) as ResponseEntity;

  return (response.payload || []) as DisplayCategory[];
};

export default CategoryApi;
```

{% endcode %}

{% endstep %}
{% endstepper %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://tech.x2bee.com/dev-guide/pjt-prepare/publish-your-docs/store-front-framewok-next.js/04.-data-fetching/3.-next.js-restapi.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
