Skip to content

Conversation

@1jiwoo27
Copy link
Member

@1jiwoo27 1jiwoo27 commented Oct 11, 2025

📌 Related Issue

✅ Checklist

  • PR 제목의 형식을 잘 작성했나요? e.g. [Feat] PR 템플릿 작성
  • 빌드가 성공했나요? (pnpm build)
  • 이슈는 등록했나요?
  • 리뷰어와 라벨을 지정했나요?

📚 Tasks

  • 패키지 설치
  • 인터셉터 설정

Summary by CodeRabbit

  • New Features
    • 공통 API 클라이언트 도입으로 모든 요청에 인증 토큰이 자동 첨부되고 JSON 기본 헤더가 적용됩니다.
    • 환경 변수 기반 기본 주소 및 자격 증명 포함으로 로그인 상태 연동이 더 원활해집니다.
    • 401(인증 만료) 시 안내 로그를 제공해 문제 원인 파악이 쉬워집니다.
  • Chores
    • 네트워크 통신을 위한 라이브러리 의존성 추가.

@1jiwoo27 1jiwoo27 requested a review from jihun3666 October 11, 2025 16:19
@1jiwoo27 1jiwoo27 self-assigned this Oct 11, 2025
@1jiwoo27 1jiwoo27 linked an issue Oct 11, 2025 that may be closed by this pull request
@coderabbitai
Copy link

coderabbitai bot commented Oct 11, 2025

Walkthrough

Axios가 패키지로 추가되었고, 환경변수 기반 baseURL/credentials/JSON 헤더/토큰 주입(Authorization) 요청 인터셉터와 401 응답 처리 인터셉터를 포함한 사전 구성 Axios 인스턴스(api)가 생성·내보내졌습니다.

Changes

Cohort / File(s) Summary
Dependencies
package.json
axios@^1.12.2 의존성 추가. 기존 스크립트/다른 의존성 변경 없음.
API Client (Axios Instance)
src/shared/api/axios.ts
api 인스턴스 생성 및 export. baseURL을 환경변수에서 로드, withCredentials: true, 기본 Content-Type: application/json. 요청 인터셉터로 localStorage.accessToken을 Bearer 토큰으로 주입. 응답 인터셉터는 성공 패스스루, 401 시 경고 로그 후 에러 재발행.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor UI as UI/Caller
  participant AX as api (Axios)
  participant S as Server

  Note over AX: Pre-configured: baseURL, JSON headers,<br/>withCredentials

  UI->>AX: api.request(config)
  activate AX
  Note over AX: Request Interceptor<br/>- Read localStorage.accessToken<br/>- Set Authorization: Bearer ...
  AX->>S: HTTP request with headers
  S-->>AX: HTTP 2xx response
  AX-->>UI: Response passthrough
  deactivate AX

  alt Unauthorized (401)
    UI->>AX: api.request(config)
    AX->>S: HTTP request
    S-->>AX: 401 Unauthorized
    Note over AX: Log token-expired warning (ko)<br/>Re-throw error
    AX-->>UI: Promise reject (401)
  end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Suggested reviewers

  • jihun3666

Pre-merge checks and finishing touches

✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed PR 제목 '[Init] axios 세팅'은 axios 설치와 인스턴스 생성이라는 주요 변경사항을 정확하게 요약하며 간결하고 명확합니다.
Linked Issues Check ✅ Passed 이 PR은 axios 패키지 설치와 인스턴스 생성 파일 추가를 통해 이슈 #11의 요구사항을 모두 충족합니다.
Out of Scope Changes Check ✅ Passed 패키지 추가와 인스턴스 생성 외에 다른 변경사항이 없어 이슈 범위를 벗어난 수정이 없습니다.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch init/axios/#11

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (5)
src/shared/api/axios.ts (5)

6-8: 기본 Content-Type 헤더 설정을 재검토하세요.

모든 요청에 application/json을 기본값으로 설정하면 파일 업로드나 폼 데이터 전송 시 문제가 발생할 수 있습니다. 필요한 경우 요청별로 헤더를 오버라이드할 수 있지만, 기본 헤더를 제거하거나 조건부로 설정하는 것을 고려하세요.


3-9: timeout 설정 및 타입 안정성을 개선하세요.

다음 개선 사항을 고려하세요:

  • 네트워크 요청에 대한 타임아웃을 추가하여 무한 대기를 방지
  • TypeScript 타입 안정성을 위해 명시적 타입 어노테이션 추가

다음 diff를 적용하여 개선하세요:

+import type { AxiosInstance } from "axios";
 import axios from "axios";

-export const api = axios.create({
+export const api: AxiosInstance = axios.create({
   baseURL: import.meta.env.VITE_BASE_URL,
   withCredentials: true,
+  timeout: 10000,
   headers: {
     "Content-Type": "application/json",
   },
 });

11-15: localStorage 접근에 대한 에러 핸들링을 추가하세요.

SSR 환경이나 일부 브라우저 설정에서 localStorage 접근이 실패할 수 있습니다. try-catch로 감싸 안정성을 높이세요.

다음 diff를 적용하세요:

 api.interceptors.request.use((config) => {
-  const token = localStorage.getItem("accessToken");
-  if (token) config.headers.Authorization = `Bearer ${token}`;
+  try {
+    const token = localStorage.getItem("accessToken");
+    if (token) config.headers.Authorization = `Bearer ${token}`;
+  } catch (error) {
+    console.error("localStorage 접근 실패:", error);
+  }
   return config;
 });

12-12: localStorage 키를 상수로 관리하세요.

"accessToken" 문자열을 하드코딩하면 유지보수가 어렵습니다. 상수로 정의하여 재사용성을 높이세요.

별도 파일에 상수를 정의하세요:

// src/shared/constants/storage.ts
export const STORAGE_KEYS = {
  ACCESS_TOKEN: "accessToken",
} as const;

그리고 다음과 같이 사용하세요:

+import { STORAGE_KEYS } from "@/shared/constants/storage";
+
 api.interceptors.request.use((config) => {
-  const token = localStorage.getItem("accessToken");
+  const token = localStorage.getItem(STORAGE_KEYS.ACCESS_TOKEN);
   if (token) config.headers.Authorization = `Bearer ${token}`;
   return config;
 });

20-22: 추가 HTTP 에러 처리를 고려하세요.

401 외에도 다른 HTTP 에러(403, 500, 503 등)에 대한 처리를 추가하면 사용자 경험이 개선됩니다. 예를 들어, 네트워크 에러나 서버 에러에 대한 통합 에러 토스트를 표시할 수 있습니다.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1af9d12 and 938cdfb.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (2)
  • package.json (1 hunks)
  • src/shared/api/axios.ts (1 hunks)
🔇 Additional comments (1)
package.json (1)

14-14: LGTM!

axios 최신 버전(1.12.2)이 올바르게 추가되었습니다.

@1jiwoo27 1jiwoo27 merged commit e8204e2 into develop Oct 11, 2025
2 checks passed
@1jiwoo27 1jiwoo27 deleted the init/axios/#11 branch October 11, 2025 16:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Init] axios 세팅

2 participants