Skip to content

Feat/axios interceptor#13

Merged
dasosann merged 5 commits into
mainfrom
feat/axios_interceptor
Jan 26, 2026
Merged

Feat/axios interceptor#13
dasosann merged 5 commits into
mainfrom
feat/axios_interceptor

Conversation

@dasosann

@dasosann dasosann commented Jan 26, 2026

Copy link
Copy Markdown
Contributor

PR Type

Enhancement


Description

  • Axios 인스턴스와 인터셉터 구현으로 API 요청 관리 체계화

  • 클라이언트/서버 환경 분리 및 401 토큰 자동 재발급 처리

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

  • 서버 환경에서 쿠키 기반 인증 처리 로직 구현


Diagram Walkthrough

flowchart LR
  A["API 요청"] --> B["클라이언트/서버 분기"]
  B --> C["CSR: api 인스턴스"]
  B --> D["SSR: serverApi 인스턴스"]
  C --> E["응답 인터셉터"]
  D --> F["요청 인터셉터<br/>쿠키 선별"]
  D --> G["응답 인터셉터"]
  E --> H["401 에러 처리"]
  F --> I["인증 쿠키 전송"]
  G --> H
  H --> J["토큰 재발급"]
  J --> K["원래 요청 재시도"]
Loading

File Walkthrough

Relevant files
Enhancement
axios.ts
클라이언트용 Axios 인스턴스 및 토큰 재발급 인터셉터                                                   

lib/axios.ts

  • Axios 클라이언트 인스턴스 생성 및 공통 설정 (baseURL, 헤더, withCredentials)
  • 응답 인터셉터로 401 에러 감지 시 토큰 자동 재발급 로직 구현
  • 재발급 실패 시 로그인 페이지로 리다이렉트 처리
  • 재시도 플래그(_retry)로 무한 루프 방지
+42/-0   
server-api.ts
서버 환경 API 클라이언트 및 쿠키 기반 인증                                                             

lib/server-api.ts

  • 서버 환경 전용 Axios 인스턴스 생성 (타임아웃 설정)
  • 요청 인터셉터에서 쿠키 저장소에서 인증 쿠키만 선별하여 헤더에 추가
  • 응답 인터셉터로 401 에러 시 토큰 재발급 및 원래 요청 재시도
  • 제네릭 request() 함수와 HTTP 메서드별 래퍼 함수(get, post, put, delete, patch) 제공
  • 에러 로깅 및 상세한 에러 정보 전달
+130/-0 
Dependencies
package.json
API 관리 및 개발 도구 의존성 추가                                                                       

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

  • TanStack Query 관련 패키지 잠금 버전 추가 (query-core, react-query,
    react-query-devtools)
  • Axios 및 관련 의존성 잠금 버전 추가 (follow-redirects, form-data, proxy-from-env)
  • 부가 의존성 추가 (asynckit, combined-stream, delayed-stream, mime-types,
    mime-db)
+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!

이 PR은 Axios와 React Query를 활용하여 프로젝트의 API 통신 계층을 구축합니다. 클라이언트 측과 서버 측 요청을 위한 명확하게 분리된 API 인스턴스를 제공하며, 특히 서버 측 요청 시 쿠키 처리를 자동화하여 데이터 관리의 효율성과 일관성을 높입니다. 이는 향후 애플리케이션의 데이터 페칭 및 상태 관리 기반을 마련합니다.

Highlights

  • Axios 인스턴스 설정: Axios를 사용하여 API 요청을 처리하는 공통 인스턴스를 설정했습니다. 이 인스턴스는 기본 URL, JSON 콘텐츠 타입 헤더, 그리고 자격 증명(쿠키)을 포함하도록 구성되었습니다.
  • 클라이언트 및 서버 API 클라이언트 분리: 클라이언트(CSR) 환경과 서버(SSR) 환경을 위한 별도의 API 클라이언트를 정의했습니다. 서버용 API 클라이언트는 next/headers를 통해 요청에 자동으로 쿠키를 포함하도록 구현되었습니다.
  • 새로운 의존성 추가: axios, @tanstack/react-query, @tanstack/react-query-devtools 라이브러리를 프로젝트에 추가하여 API 통신 및 데이터 페칭/상태 관리 기능을 도입했습니다.
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.

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

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.

Code Review

PR 제목과 설명에 따라 Axios 인스턴스 및 서버 API 클라이언트 구현, TanStack Query 의존성 추가, 서버 환경 쿠키 자동 포함 기능 지원 등 전반적으로 잘 구현되었습니다. 특히 Next.js 15+의 cookies() 비동기 처리와 unknown 타입을 활용한 타입 안정성 확보는 모범적인 사례입니다.

Comment thread lib/axios.ts
Comment thread lib/server-api.ts Outdated
@dasosann

Copy link
Copy Markdown
Contributor Author

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

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

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.

Code Review

Axios 인터셉터를 활용하여 클라이언트와 서버 환경에 맞는 API 클라이언트를 구현하신 점이 좋습니다. 특히 서버 환경에서 next/headerscookies()를 사용하여 인증 정보를 전달하는 로직이 인상적입니다. 코드의 재사용성과 보안을 더욱 향상시키기 위해 몇 가지 제안 사항을 남깁니다. 서버 전용 환경 변수 사용, 쿠키 전달 방식 개선, API 클라이언트의 역할 분리 등을 고려해보시면 좋겠습니다. 또한, 코드 중복을 줄여 유지보수성을 높이는 리팩터링도 제안 드립니다.

Comment thread lib/server-api.ts
Comment on lines +24 to +29
const cookieStore = await cookies();
const allCookies = cookieStore.toString(); // "key=value; key2=value2" 형태

if (allCookies) {
config.headers.Cookie = allCookies;
}

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

cookieStore.toString()을 사용하여 모든 쿠키를 API 요청 헤더에 그대로 전달하는 방식은 보안 및 성능상 잠재적인 위험을 가집니다.

이 방식은 API 인증과 무관한 제3자 서비스(예: 분석 도구)의 쿠키까지 백엔드 서버로 전송하여 불필요한 데이터를 노출할 수 있으며, 헤더 크기 제한을 초과할 위험도 있습니다.

필요한 세션 또는 인증 토큰 쿠키(예: accessToken)만 선별하여 전달하는 방식으로 리팩터링하는 것을 강력히 권장합니다.

Suggested change
const cookieStore = await cookies();
const allCookies = cookieStore.toString(); // "key=value; key2=value2" 형태
if (allCookies) {
config.headers.Cookie = allCookies;
}
const cookieStore = await cookies();
const sessionCookie = cookieStore.get("session-token"); // 예시: 실제 사용하는 인증 쿠키 이름으로 변경하세요.
if (sessionCookie) {
config.headers.Cookie = `${sessionCookie.name}=${sessionCookie.value}`;
}

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.

수정완료

Comment thread lib/server-api.ts Outdated
Comment thread lib/server-api.ts
Comment thread lib/server-api.ts Outdated
});

// 에러를 던져서 상위 컴포넌트나 Error Boundary가 처리하게 함
throw new Error(errorMessage);

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

throw new Error(errorMessage)로 새로운 에러를 생성하여 던지면, 원래 axios 에러가 가지고 있던 상태 코드(status)나 다른 유용한 컨텍스트 정보가 손실됩니다.

에러를 처리하는 상위 컴포넌트(error.tsx 등)에서 상태 코드에 따라 다른 UI를 보여주기 어려워집니다.

console.error로 이미 상세 정보를 로깅하고 있으므로, 여기서는 원본 error 객체를 그대로 다시 던져 호출자가 전체 컨텍스트를 활용할 수 있도록 하는 것이 좋습니다.

Suggested change
throw new Error(errorMessage);
throw error;

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.

수정완료

Comment thread lib/server-api.ts
@dasosann

Copy link
Copy Markdown
Contributor Author

@gemini-code-assist review

@dasosann

Copy link
Copy Markdown
Contributor Author

/describe

@qodo-code-review

qodo-code-review Bot commented Jan 26, 2026

Copy link
Copy Markdown

PR Description updated to latest commit (627c954)

Comment thread lib/axios.ts

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 (+42/-0)
클라이언트용 Axios 인스턴스 및 토큰 재발급 인터셉터                                                   

lib/axios.ts

  • Axios 클라이언트 인스턴스 생성 및 공통 설정 (baseURL, 헤더, withCredentials)
  • 응답 인터셉터로 401 에러 감지 시 토큰 자동 재발급 로직 구현
  • 재발급 실패 시 로그인 페이지로 리다이렉트 처리
  • 재시도 플래그(_retry)로 무한 루프 방지
server-api.ts (+130/-0)
서버 환경 API 클라이언트 및 쿠키 기반 인증                                                             

lib/server-api.ts

  • 서버 환경 전용 Axios 인스턴스 생성 (타임아웃 설정)
  • 요청 인터셉터에서 쿠키 저장소에서 인증 쿠키만 선별하여 헤더에 추가
  • 응답 인터셉터로 401 에러 시 토큰 재발급 및 원래 요청 재시도
  • 제네릭 request() 함수와 HTTP 메서드별 래퍼 함수(get, post, put, delete, patch) 제공
  • 에러 로깅 및 상세한 에러 정보 전달
Dependencies
package.json (+3/-0)
API 관리 및 개발 도구 의존성 추가                                                                       

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

  • TanStack Query 관련 패키지 잠금 버전 추가 (query-core, react-query,
    react-query-devtools)
  • Axios 및 관련 의존성 잠금 버전 추가 (follow-redirects, form-data, proxy-from-env)
  • 부가 의존성 추가 (asynckit, combined-stream, delayed-stream, mime-types,
    mime-db)

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

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.

Code Review

이번 PR은 Axios 인스턴스 및 서버 API 클라이언트 구현, 그리고 TanStack Query 의존성 추가를 통해 API 통신 및 상태 관리의 기반을 마련했습니다. 클라이언트와 서버 환경에 맞는 Axios 설정을 분리하고, 인증 토큰 재발급 로직을 인터셉터로 처리한 점은 매우 긍정적입니다. 전반적으로 잘 구성된 PR이지만, 몇 가지 개선 사항을 제안합니다. 특히 하드코딩된 문자열을 상수로 분리하고, 타입 안정성을 높이는 방향으로 코드를 개선하면 유지보수성과 견고성을 더욱 향상시킬 수 있습니다.

Comment thread lib/axios.ts
Comment thread lib/axios.ts
if (
error.response?.status === 401 &&
!originalRequest._retry &&
originalRequest.url !== "/api/auth/login"

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

인증 관련 경로("/api/auth/login")가 코드 내에 하드코딩되어 있습니다. 이러한 문자열 리터럴은 변경될 가능성이 있으며, 여러 곳에서 사용될 경우 일관성 유지에 어려움이 있습니다. 이를 별도의 상수로 분리하여 관리하면 코드의 유연성과 유지보수성이 향상됩니다.

Suggested change
originalRequest.url !== "/api/auth/login"
originalRequest.url !== AUTH_LOGIN_API_PATH

Comment thread lib/axios.ts
Comment thread lib/server-api.ts
Comment thread lib/server-api.ts
Comment thread lib/server-api.ts
Comment thread lib/server-api.ts
Comment on lines +105 to +109
console.error(`[Server API Error] ${method} ${path}`, {
status,
message: errorMessage,
data: error.response?.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

console.error를 사용하여 에러를 로깅하는 것은 개발 환경에서는 유용하지만, 프로덕션 환경에서는 Sentry와 같은 중앙 집중식 로깅/에러 모니터링 솔루션을 사용하는 것이 더 효과적입니다. 현재 구현은 기능적으로 문제가 없으나, 향후 운영을 위해 고려해볼 사항입니다.

Suggested change
console.error(`[Server API Error] ${method} ${path}`, {
status,
message: errorMessage,
data: error.response?.data,
});
// 프로덕션 환경에서는 Sentry 등 중앙 집중식 로깅 솔루션 사용을 고려
console.error(`[Server API Error] ${method} ${path}`, {
status,
message: errorMessage,
data: error.response?.data,
});

Comment thread lib/server-api.ts
@dasosann dasosann merged commit 5b37fc6 into main Jan 26, 2026
2 checks passed
@dasosann dasosann deleted the feat/axios_interceptor branch January 26, 2026 08:24
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