Skip to content

Feat/axios interceptor#12

Closed
dasosann wants to merge 3 commits intomainfrom
feat/axios_interceptor
Closed

Feat/axios interceptor#12
dasosann wants to merge 3 commits intomainfrom
feat/axios_interceptor

Conversation

@dasosann
Copy link
Copy Markdown
Contributor

@dasosann dasosann commented Jan 26, 2026

PR Type

Enhancement


Description

  • Axios 인스턴스 및 서버 API 클라이언트 구현

  • 클라이언트/서버 환경 분리 요청 처리

  • React Query 및 개발자 도구 의존성 추가

  • 자동 쿠키 관리 기능 포함


Diagram Walkthrough

flowchart LR
  A["Axios Config"] --> B["Client Instance<br/>api"]
  A --> C["Server API<br/>serverApi"]
  C --> D["Request Handler<br/>with Cookies"]
  D --> E["HTTP Methods<br/>GET/POST/PUT/DELETE/PATCH"]
  F["React Query"] --> G["Data Fetching"]
  H["React Query DevTools"] --> G
Loading

File Walkthrough

Relevant files
Enhancement
axios.ts
Axios 클라이언트 인스턴스 설정                                                                           

lib/axios.ts

  • Axios 인스턴스 생성 및 공통 설정 정의
  • baseURL, Content-Type 헤더, withCredentials 설정
  • 클라이언트 환경용 api 인스턴스 export
+11/-0   
server-api.ts
서버 환경 API 클라이언트 구현                                                                             

lib/server-api.ts

  • 서버 환경용 API 클라이언트 구현
  • next/headers의 cookies() 활용한 자동 쿠키 주입
  • GET, POST, PUT, DELETE, PATCH 메서드 제공
  • 제네릭 타입 지원으로 응답 타입 안정성 확보
+46/-0   
Dependencies
package.json
React Query 및 Axios 의존성 추가                                                             

package.json

  • @tanstack/react-query@^5.90.20 추가
  • @tanstack/react-query-devtools@^5.91.2 추가
  • axios@^1.13.3 추가
+3/-0     
pnpm-lock.yaml
패키지 잠금 파일 업데이트                                                                                     

pnpm-lock.yaml

  • React Query 및 관련 패키지 잠금 파일 업데이트
  • Axios 및 의존성(follow-redirects, form-data) 추가
  • mime-types, proxy-from-env 등 보조 패키지 포함
+113/-0 


✨ Describe tool usage guide:

Overview:
The describe tool scans the PR code changes, and generates a description for the PR - title, type, summary, walkthrough and labels. The tool can be triggered automatically every time a new PR is opened, or can be invoked manually by commenting on a PR.

When commenting, to edit configurations related to the describe tool (pr_description section), use the following template:

/describe --pr_description.some_config1=... --pr_description.some_config2=...

With a configuration file, use the following template:

[pr_description]
some_config1=...
some_config2=...
Enabling\disabling automation
  • When you first install the app, the default mode for the describe tool is:
pr_commands = ["/describe", ...]

meaning the describe tool will run automatically on every PR.

  • Markers are an alternative way to control the generated description, to give maximal control to the user. If you set:
pr_commands = ["/describe --pr_description.use_description_markers=true", ...]

the tool will replace every marker of the form pr_agent:marker_name in the PR description with the relevant content, where marker_name is one of the following:

  • type: the PR type.
  • summary: the PR summary.
  • walkthrough: the PR walkthrough.
  • diagram: the PR sequence diagram (if enabled).

Note that when markers are enabled, if the original PR description does not contain any markers, the tool will not alter the description at all.

Custom labels

The default labels of the describe tool are quite generic: [Bug fix, Tests, Enhancement, Documentation, Other].

If you specify custom labels in the repo's labels page or via configuration file, you can get tailored labels for your use cases.
Examples for custom labels:

  • Main topic:performance - pr_agent:The main topic of this PR is performance
  • New endpoint - pr_agent:A new endpoint was added in this PR
  • SQL query - pr_agent:A new SQL query was added in this PR
  • Dockerfile changes - pr_agent:The PR contains changes in the Dockerfile
  • ...

The list above is eclectic, and aims to give an idea of different possibilities. Define custom labels that are relevant for your repo and use cases.
Note that Labels are not mutually exclusive, so you can add multiple label categories.
Make sure to provide proper title, and a detailed and well-phrased description for each label, so the tool will know when to suggest it.

Inline File Walkthrough 💎

For enhanced user experience, the describe tool can add file summaries directly to the "Files changed" tab in the PR page.
This will enable you to quickly understand the changes in each file, while reviewing the code changes (diffs).

To enable inline file summary, set pr_description.inline_file_summary in the configuration file, possible values are:

  • 'table': File changes walkthrough table will be displayed on the top of the "Files changed" tab, in addition to the "Conversation" tab.
  • true: A collapsable file comment with changes title and a changes summary for each file in the PR.
  • false (default): File changes walkthrough will be added only to the "Conversation" tab.
Utilizing extra instructions

The describe tool can be configured with extra instructions, to guide the model to a feedback tailored to the needs of your project.

Be specific, clear, and concise in the instructions. With extra instructions, you are the prompter. Notice that the general structure of the description is fixed, and cannot be changed. Extra instructions can change the content or style of each sub-section of the PR description.

Examples for extra instructions:

[pr_description]
extra_instructions="""- The PR title should be in the format: '<PR type>: <title>'
- The title should be short and concise (up to 10 words)
- ...
"""

Use triple quotes to write multi-line instructions. Use bullet points to make the instructions more readable.

More PR-Agent commands

To invoke the PR-Agent, add a comment using one of the following commands:

  • /review: Request a review of your Pull Request.
  • /describe: Update the PR title and description based on the contents of the PR.
  • /improve [--extended]: Suggest code improvements. Extended mode provides a higher quality feedback.
  • /ask <QUESTION>: Ask a question about the PR.
  • /update_changelog: Update the changelog based on the PR's contents.
  • /help_docs <QUESTION>: Given a path to documentation (either for this repository or for a given one), ask a question.
  • /add_docs 💎: Generate docstring for new components introduced in the PR.
  • /generate_labels 💎: Generate labels for the PR based on the PR's contents.
  • /analyze 💎: Automatically analyzes the PR, and presents changes walkthrough for each component.

See the tools guide for more details.
To list the possible configuration parameters, add a /config comment.

See the describe usage page for a comprehensive guide on using this tool.

@qodo-code-review qodo-code-review bot added the enhancement New feature or request label Jan 26, 2026
@gemini-code-assist
Copy link
Copy Markdown
Contributor

Summary of Changes

Hello @dasosann, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request establishes a foundational layer for API communication by integrating Axios and Tanstack Query. It provides a dedicated client-side Axios instance for general requests and a specialized server-side utility to ensure proper cookie forwarding, which is crucial for authenticated server-rendered pages. This setup aims to streamline data fetching and management across the application's client and server environments.

Highlights

  • Axios Integration: Introduced Axios for making HTTP requests, establishing a standardized approach for API communication within the application.
  • Client-Side API Instance: A new api instance in lib/axios.ts is configured with a base URL, JSON content type, and withCredentials for client-side requests.
  • Server-Side API Utility: A serverApi function in lib/server-api.ts was added to facilitate server-side API calls, specifically designed to automatically forward cookies from the server context.
  • Dependency Management: Added axios, @tanstack/react-query, and @tanstack/react-query-devtools to the project dependencies to support robust data fetching and debugging capabilities.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

Axios 인스턴스와 서버/클라이언트 API 요청 구조를 추가하고, React Query 관련 의존성을 설치하는 PR입니다. 전반적으로 좋은 방향이지만, 몇 가지 개선점을 제안합니다. server-api.ts의 경우 현재 GET 요청만 처리 가능하여 확장성이 부족하므로, POST, PUT 등 다른 HTTP 메소드도 지원하는 범용적인 구조로 리팩토링하는 것이 좋습니다. 또한, package.json에 명시된 axios 버전이 공식적으로 존재하지 않는 버전으로 보여, 보안 및 안정성을 위해 최신 안정 버전으로 업데이트하는 것을 권장하며, 이러한 공유 설정 파일 변경은 팀과 논의가 필요합니다. 자세한 내용은 각 파일의 리뷰 코멘트를 참고해주세요.

Comment on lines +1 to +16
import { cookies } from "next/headers";
import { api } from "./axios";
import type { AxiosRequestConfig } from "axios";

export async function serverApi(url: string, options: AxiosRequestConfig = {}) {
const cookieStore = await cookies();

// 기존 api 인스턴스를 쓰되, 쿠키 헤더만 쓱 끼워넣기
return api.get(url, {
...options,
headers: {
...options.headers, // 기존 헤더 유지
Cookie: cookieStore.toString(), // 쿠키 추가
},
});
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

현재 serverApi 함수는 GET 요청에만 사용 가능하도록 하드코딩되어 있습니다. 이는 향후 POST, PUT, DELETE 등 다른 HTTP 메소드를 사용해야 할 때 코드 중복을 유발하고 확장성을 저해할 수 있습니다. 보다 일반적이고 재사용 가능한 구조로 리팩토링하는 것을 강력히 권장합니다. 예를 들어, serverApi를 각 HTTP 메소드를 지원하는 함수를 가진 객체로 만들면 API의 일관성을 유지하고, 새로운 HTTP 메소드가 필요할 때 쉽게 확장할 수 있습니다.

import { cookies } from "next/headers";
import { api } from "./axios";
import type { AxiosRequestConfig, AxiosResponse } from "axios";

// 서버 환경에서 사용할 API 클라이언트입니다.
// next/headers의 cookies()를 사용하여 요청에 자동으로 쿠키를 포함시킵니다.
async function request<T>(config: AxiosRequestConfig): Promise<AxiosResponse<T>> {
  const cookieStore = await cookies();
  const cookieHeader = cookieStore.toString();

  return api({
    ...config,
    headers: {
      ...config.headers,
      ...(cookieHeader && { Cookie: cookieHeader }),
    },
  });
}

export const serverApi = {
  get: <T = any>(url: string, config?: AxiosRequestConfig) =>
    request<T>({ ...config, method: "GET", url }),

  post: <T = any>(url: string, data?: any, config?: AxiosRequestConfig) =>
    request<T>({ ...config, method: "POST", url, data }),

  put: <T = any>(url: string, data?: any, config?: AxiosRequestConfig) =>
    request<T>({ ...config, method: "PUT", url, data }),

  delete: <T = any>(url: string, config?: AxiosRequestConfig) =>
    request<T>({ ...config, method: "DELETE", url }),

  patch: <T = any>(url: string, data?: any, config?: AxiosRequestConfig) =>
    request<T>({ ...config, method: "PATCH", url, data }),
};
References
  1. 함수 이름이 의미론적이어야 하며(52), 코드 중복을 피하기 위해 재사용 가능한 유틸리티로 추출해야 합니다(54). 현재 serverApi는 GET만 지원하여 이름이 오해의 소지가 있고, 다른 메소드 추가 시 코드 중복이 발생할 수 있습니다. (link)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

반영함

@dasosann
Copy link
Copy Markdown
Contributor Author

@gemini-code-assist review

@dasosann
Copy link
Copy Markdown
Contributor Author

/describe

@dasosann
Copy link
Copy Markdown
Contributor Author

@gemini-code-assist 다시 리뷰해줘

@qodo-code-review
Copy link
Copy Markdown

qodo-code-review bot commented Jan 26, 2026

PR Description updated to latest commit (f3d8e71)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

File Walkthrough

Enhancement
axios.ts (+11/-0)
Axios 클라이언트 인스턴스 설정                                                                           

lib/axios.ts

  • Axios 인스턴스 생성 및 공통 설정 정의
  • baseURL, Content-Type 헤더, withCredentials 설정
  • 클라이언트 환경용 api 인스턴스 export
server-api.ts (+46/-0)
서버 환경 API 클라이언트 구현                                                                             

lib/server-api.ts

  • 서버 환경용 API 클라이언트 구현
  • next/headers의 cookies() 활용한 자동 쿠키 주입
  • GET, POST, PUT, DELETE, PATCH 메서드 제공
  • 제네릭 타입 지원으로 응답 타입 안정성 확보
Dependencies
package.json (+3/-0)
React Query 및 Axios 의존성 추가                                                             

package.json

  • @tanstack/react-query@^5.90.20 추가
  • @tanstack/react-query-devtools@^5.91.2 추가
  • axios@^1.13.3 추가
pnpm-lock.yaml (+113/-0)
패키지 잠금 파일 업데이트                                                                                     

pnpm-lock.yaml

  • React Query 및 관련 패키지 잠금 파일 업데이트
  • Axios 및 의존성(follow-redirects, form-data) 추가
  • mime-types, proxy-from-env 등 보조 패키지 포함

Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

안녕하세요. Axios 인터셉터 및 API 클라이언트 구조 개선을 위한 PR 잘 보았습니다. 클라이언트와 서버 환경을 분리하여 API 요청을 처리하는 구조를 도입하고, TanStack React Query를 추가하여 데이터 페칭의 기반을 마련한 점이 인상적입니다. 코드 리뷰 결과, 서버 API에서 쿠키를 처리하는 방식에 치명적인 오류가 발견되었으며, 타입스크립트 타입을 개선하여 안정성과 개발 경험을 높일 수 있는 몇 가지 사항을 제안드립니다. 자세한 내용은 각 파일의 주석을 참고해주세요.

Comment on lines +10 to +11
const cookieStore = await cookies();
const cookieHeader = cookieStore.toString();
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

critical

안녕하세요. cookies()에서 반환된 cookieStore 객체에 toString() 메서드를 사용하는 것은 쿠키 문자열을 직렬화하는 안정적인 방법이 아닙니다. ReadonlyRequestCookies 타입에는 toString()이 공식적으로 정의되어 있지 않아 예상치 못한 동작이나 오류를 발생시킬 수 있습니다.

cookieStore.getAll()을 사용하여 모든 쿠키를 배열로 가져온 후, 이를 key=value 형태의 문자열로 조합하여 Cookie 헤더를 생성하는 것이 올바른 방법입니다. 아래 제안 코드를 참고하여 수정하시는 것을 권장합니다.

  const cookieStore = await cookies();
  const cookieHeader = cookieStore
    .getAll()
    .map((cookie) => `${cookie.name}=${cookie.value}`)
    .join("; ");

Comment on lines +26 to +30
post: <T = unknown>(
url: string,
data?: unknown,
config?: AxiosRequestConfig,
) => request<T>({ ...config, method: "POST", url, data }),
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

타입 안정성 및 개발자 경험 향상을 위해 post 메서드의 data 파라미터 타입을 unknown 대신 제네릭 D로 지정하는 것을 제안합니다. 이렇게 하면 serverApi.post를 호출하는 쪽에서 요청 본문의 타입을 명시할 수 있어 타입 추론이 더 원활해지고 코드의 안정성이 높아집니다. 이는 레포지토리 스타일 가이드에서 강조하는 타입 안정성 원칙과도 부합합니다. put, patch 메서드에도 동일하게 적용할 수 있습니다.

  post: <T = unknown, D = unknown>(
    url: string,
    data?: D,
    config?: AxiosRequestConfig,
  ) => request<T>({ ...config, method: "POST", url, data }),
References
  1. Server Actions 함수는 인자와 반환값에 대한 명확한 타입을 가져야 합니다. 이 원칙은 서버 환경 API 클라이언트에도 동일하게 적용하여 타입 안정성을 높이는 것이 좋습니다. (link)
  2. any 타입 사용을 금지하고, unknown이나 never를 활용하여 타입을 좁히도록 권장합니다. 제네릭을 활용하면 unknown보다 더 구체적인 타입 추론이 가능해져 코드의 안정성을 높일 수 있습니다. (link)

Comment on lines +32 to +36
put: <T = unknown>(
url: string,
data?: unknown,
config?: AxiosRequestConfig,
) => request<T>({ ...config, method: "PUT", url, data }),
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

타입 안정성 및 개발자 경험 향상을 위해 put 메서드의 data 파라미터 타입을 unknown 대신 제네릭 D로 지정하는 것을 제안합니다. 이렇게 하면 serverApi.put을 호출하는 쪽에서 요청 본문의 타입을 명시할 수 있어 타입 추론이 더 원활해지고 코드의 안정성이 높아집니다. 이는 레포지토리 스타일 가이드에서 강조하는 타입 안정성 원칙과도 부합합니다.

  put: <T = unknown, D = unknown>(
    url: string,
    data?: D,
    config?: AxiosRequestConfig,
  ) => request<T>({ ...config, method: "PUT", url, data }),
References
  1. Server Actions 함수는 인자와 반환값에 대한 명확한 타입을 가져야 합니다. 이 원칙은 서버 환경 API 클라이언트에도 동일하게 적용하여 타입 안정성을 높이는 것이 좋습니다. (link)
  2. any 타입 사용을 금지하고, unknown이나 never를 활용하여 타입을 좁히도록 권장합니다. 제네릭을 활용하면 unknown보다 더 구체적인 타입 추론이 가능해져 코드의 안정성을 높일 수 있습니다. (link)

Comment on lines +41 to +45
patch: <T = unknown>(
url: string,
data?: unknown,
config?: AxiosRequestConfig,
) => request<T>({ ...config, method: "PATCH", url, data }),
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

타입 안정성 및 개발자 경험 향상을 위해 patch 메서드의 data 파라미터 타입을 unknown 대신 제네릭 D로 지정하는 것을 제안합니다. 이렇게 하면 serverApi.patch를 호출하는 쪽에서 요청 본문의 타입을 명시할 수 있어 타입 추론이 더 원활해지고 코드의 안정성이 높아집니다. 이는 레포지토리 스타일 가이드에서 강조하는 타입 안정성 원칙과도 부합합니다.

  patch: <T = unknown, D = unknown>(
    url: string,
    data?: D,
    config?: AxiosRequestConfig,
  ) => request<T>({ ...config, method: "PATCH", url, data }),
References
  1. Server Actions 함수는 인자와 반환값에 대한 명확한 타입을 가져야 합니다. 이 원칙은 서버 환경 API 클라이언트에도 동일하게 적용하여 타입 안정성을 높이는 것이 좋습니다. (link)
  2. any 타입 사용을 금지하고, unknown이나 never를 활용하여 타입을 좁히도록 권장합니다. 제네릭을 활용하면 unknown보다 더 구체적인 타입 추론이 가능해져 코드의 안정성을 높일 수 있습니다. (link)

Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

이번 PR은 Axios 인스턴스 및 서버 API 클라이언트를 구현하고, React Query 및 개발자 도구 의존성을 추가하여 클라이언트/서버 환경 분리 요청 처리를 지원하는 중요한 개선 사항입니다. 특히 lib/axios.tslib/server-api.ts로 클라이언트와 서버 환경의 API 호출을 명확히 분리한 점은 코드 구성 측면에서 매우 긍정적입니다. Next.js 15+의 await cookies() 사용과 제네릭 타입을 통한 응답 타입 안정성 확보도 잘 이루어졌습니다. 전반적으로 코드 품질과 유지보수성을 높이는 좋은 변경입니다.

@@ -0,0 +1,46 @@
import { cookies } from "next/headers";
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

cookies() 함수는 Next.js의 Server Components 또는 Server Actions에서만 호출되어야 합니다. 현재 lib/server-api.ts 파일은 서버 환경에서만 사용될 것으로 예상되지만, 실수로 클라이언트 컴포넌트에서 이 파일을 import 하여 request 함수를 호출할 경우 런타임 에러가 발생할 수 있습니다. 이를 방지하고 파일의 의도를 명확히 하기 위해 파일 상단에 'use server' 지시어를 추가하여 해당 파일이 Server Action으로 동작하도록 명시하는 것을 권장합니다. 이는 빌드 시점에 잠재적인 문제를 감지하는 데 도움이 됩니다.

Repository Style Guide 2.2

Suggested change
import { cookies } from "next/headers";
'use server';
import { cookies } from "next/headers";

const axiosConfig = {
baseURL: process.env.NEXT_PUBLIC_API_URL,
headers: { "Content-Type": "application/json" },
withCredentials: true,
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

클라이언트 환경에서 withCredentials: true 설정은 브라우저가 자동으로 쿠키를 포함하도록 하여 유용합니다. 하지만 이 axiosConfig를 사용하여 생성된 api 인스턴스가 lib/server-api.ts에서 서버 환경 요청에도 재사용되고 있습니다. 서버 환경에서는 withCredentials 설정이 무의미하며, next/headerscookies()를 통해 쿠키를 수동으로 주입하는 방식이 올바릅니다. 코드의 의도를 더욱 명확히 하고 잠재적인 혼란을 방지하기 위해, 서버 전용 axios 인스턴스를 따로 생성하여 withCredentials: false로 설정하거나, axiosConfig에서 withCredentials를 제거하고 클라이언트용 api 인스턴스 생성 시에만 명시적으로 withCredentials: true를 적용하는 것을 고려해볼 수 있습니다. 현재 구현 방식이 동작에는 문제가 없을 수 있으나, 명확성을 위해 제안합니다.

@dasosann dasosann closed this Jan 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant