Skip to content

[Refactor] 인증 아키텍처 개선 - Axios 인스턴스 수정 및 refresh 주체 변경#388

Merged
Chiman2937 merged 8 commits intomainfrom
chiyoung-refactor/auth
Feb 21, 2026
Merged

[Refactor] 인증 아키텍처 개선 - Axios 인스턴스 수정 및 refresh 주체 변경#388
Chiman2937 merged 8 commits intomainfrom
chiyoung-refactor/auth

Conversation

@Chiman2937
Copy link
Member

@Chiman2937 Chiman2937 commented Feb 21, 2026

📝 변경 사항

인증 로직 리팩토링 변경사항

브랜치: chiyoung-refactor/auth
커밋 범위: 119b45f ~ aa13479 (5개 커밋)
변경 파일: 5개 (49 additions, 47 deletions)


커밋 히스토리

커밋 메시지
119b45f fix: LoginResponse 타입 수정 - expiresAt 추가
51b60c5 fix: 페이지 새로고침 시 refresh 주체를 AuthProvider에서 proxy.ts로 변경
eb13534 fix: authAPI => refreshAPI로 수정, refresh 제외 나머지 인증 관련 API는 baseAPI 실행되도록 수정
98f2c77 fix: proxy.ts refresh 로직 실패 에러 핸들링 구문 추가
aa13479 fix: proxy.ts set-cookie 로직에 domain 속성 추가

1. Refresh 로직 주체 변경 - AuthProvider → proxy.ts

페이지 새로고침 시 accessToken 재발급(refresh) 로직의 실행 주체를 AuthProvider(클라이언트)에서 proxy.ts(미들웨어, 서버)로 변경.

Before - AuthProvider에서 refresh 수행

// src/providers/provider-auth/index.tsx
export const AuthProvider = ({ children, hasRefreshToken }: Props) => {
  const [isAuthenticated, setIsAuthenticated] = useState(hasRefreshToken);

  useEffect(() => {
    const updateAuthenticated = async () => {
      const hasAccessToken = !!Cookies.get('accessToken');
      if (!hasAccessToken && hasRefreshToken) {
        try {
          await API.authService.refresh();
          setIsAuthenticated(true);
        } catch {
          setIsAuthenticated(false);
        }
      } else if (hasAccessToken) {
        setIsAuthenticated(true);
      }
    };
    updateAuthenticated();
  }, [hasRefreshToken]);
  // ...
};

After - proxy.ts에서 refresh 수행

// src/proxy.ts
export const proxy = async (request: NextRequest) => {
  const accessToken = request.cookies.get('accessToken');
  const refreshToken = request.cookies.get('refreshToken');
  let hasValidToken = !!accessToken;

  const response = NextResponse.next();

  // accessToken이 없으면 refresh 실행하여 응답에 set cookie 설정
  if (!accessToken && refreshToken) {
    try {
      const data = await API.authService.refresh();
      hasValidToken = true;
      response.cookies.set('accessToken', data.accessToken, {
        httpOnly: false,
        maxAge: data.expiresIn,
        domain: 'wego.monster',
      });
    } catch {
      hasValidToken = false;
    }
  }
  // ...
};

변경 이유

  • AuthProvider (클라이언트): useEffect에서 refresh를 수행하면 컴포넌트 마운트 이후에 실행되므로, 초기 렌더링 시 인증 상태가 불확실한 구간이 발생
  • proxy.ts (미들웨어): 페이지 요청 전에 서버에서 refresh가 완료되므로, 클라이언트에 도달하기 전에 accessToken이 갱신됨

AuthProvider 변경사항

  • useEffect 내 refresh 로직 전체 삭제
  • js-cookie import 제거
  • API import 제거
  • isAuthenticated 상태 관리 역할은 유지 (외부에서 setIsAuthenticated로 제어)

2. LoginResponse 타입 수정

src/types/service/auth.tsLoginResponse 인터페이스에 expiresAt 필드 추가.

export interface LoginResponse {
  accessToken: string;
  tokenType: 'Bearer';
  expiresIn: number;
  expiresAt: string;   // 추가
  user: {
    userId: number;
    email: string;
    // ...
  };
}

3. authAPI → refreshAPI 변경

src/api/core/auth/index.tssrc/api/core/refresh/index.ts로 파일 이동 및 이름 변경.

변경 이유

기존 authAPI는 인증 관련 API(login, signup, logout, refresh 등) 전용 인스턴스였으나, 실제로 별도의 axios 인스턴스가 필요한 것은 refresh API만 해당. refresh가 서버에서 실행될 경우 refreshToken을 request header에 직접 주입해야 하기 때문.

나머지 인증 관련 API(login, signup, logout, withdraw, google OAuth)는 baseAPIwithCredentials: true 옵션만 추가하면 충분.

refreshAPI 인스턴스 변경점

// Before (authAPI) - accessToken 설정 로직 포함
authInstance.interceptors.request.use(async (config) => {
  const isServer = typeof window === 'undefined';
  if (isServer) {
    // refreshToken 쿠키 주입
  }
  const accessToken = await getAccessToken();    // ← 불필요
  if (accessToken && config.headers) {           // ← 불필요
    config.headers.Authorization = `Bearer ${accessToken}`;
  }
  return config;
});

// After (refreshAPI) - refreshToken 쿠키 주입만 담당
refreshInstance.interceptors.request.use(async (config) => {
  const isServer = typeof window === 'undefined';
  if (isServer) {
    // refreshToken 쿠키 주입
  }
  return config;
});

refresh API는 accessToken이 아닌 refreshToken만 필요하므로, getAccessToken() 로직을 제거.

auth-service import 변경

// Before - 모든 인증 API가 authAPI 사용
import { authAPI } from '@/api/core/auth';

login:   authAPI.post('/api/v1/auth/login', payload)
signup:  authAPI.post('/api/v1/auth/signup', payload)
logout:  authAPI.post('/api/v1/auth/logout', null)
refresh: authAPI.post('/api/v1/auth/refresh', null)

// After - refresh만 refreshAPI, 나머지는 baseAPI + withCredentials
import { baseAPI } from '@/api/core/base';
import { refreshAPI } from '@/api/core/refresh';

login:   baseAPI.post('/api/v1/auth/login', payload, { withCredentials: true })
signup:  baseAPI.post('/api/v1/auth/signup', payload, { withCredentials: true })
logout:  baseAPI.post('/api/v1/auth/logout', null, { withCredentials: true })
refresh: refreshAPI.post('/api/v1/auth/refresh', null, { withCredentials: true })

4. proxy.ts 인증 판단 기준 변경

기존에는 accessToken || refreshToken 존재 여부로 인증 상태를 판단했으나, 변경 후에는 refresh를 미들웨어에서 선처리하므로 hasValidToken (accessToken 존재 또는 refresh 성공 여부) 단일 변수로 판단.

// Before
if (isPublic && (accessToken || refreshToken)) { ... }   // public 페이지 접근 차단
if (!accessToken && !refreshToken) { ... }                // 로그인 리다이렉트

// After
if (isPublic && hasValidToken) { ... }                    // public 페이지 접근 차단
if (!hasValidToken) { ... }                               // 로그인 리다이렉트

refresh 로직이 미들웨어에서 선처리되므로, refreshToken 존재 여부를 별도로 체크할 필요 없이 hasValidToken 하나로 인증 상태를 판단할 수 있게 됨.


변경된 파일 목록

파일 변경 유형
src/api/core/auth/index.tssrc/api/core/refresh/index.ts 이동 및 이름 변경 (authAPI → refreshAPI, accessToken 로직 제거)
src/api/service/auth-service/index.ts 수정 (refreshAPI + baseAPI 분리 import, withCredentials 추가)
src/providers/provider-auth/index.tsx 수정 (useEffect refresh 로직 제거)
src/proxy.ts 수정 (refresh 로직 추가, 인증 판단 기준 변경)
src/types/service/auth.ts 수정 (LoginResponse에 expiresAt 추가)

🔗 관련 이슈

Closes #


🧪 테스트 방법

  • 수동 테스트 검증(로컬 환경)
  • 유닛 테스트 검증
  • 통합 테스트 검증

📸 스크린샷 (선택)


📋 체크리스트

  • 관련 문서를 업데이트했습니다 (필요한 경우)
  • 테스트를 추가/수정했습니다 (필요한 경우)
  • Breaking change가 있다면 명시했습니다

💬 추가 코멘트


CodeRabbit Review는 자동으로 실행되지 않습니다.

Review를 실행하려면 comment에 아래와 같이 작성해주세요

@coderabbitai review

Summary by CodeRabbit

릴리스 노트

  • 버그 수정

    • 인증 토큰 관리 로직을 개선하여 세션 유지 안정성 향상
    • 자격증명 기반 요청 처리로 보안성 강화
  • 개선사항

    • 토큰 갱신 메커니즘 최적화로 더 나은 사용자 경험 제공
    • 인증 흐름 간소화

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 21, 2026

Important

Review skipped

Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

Walkthrough

이 변경사항은 인증(Auth) 시스템의 토큰 갱신 흐름을 재구조화합니다. 자동 갱신 로직을 제거하고, API 인스턴스를 분리하며, 프록시 미들웨어에서 제어된 갱신을 구현하며, 자격증명 기반 요청으로 전환합니다.

Changes

Cohort / File(s) Summary
API 인스턴스 분리
src/api/core/refresh/index.ts
authInstance를 refreshInstance로 변경하고, 액세스 토큰 주입 로직을 제거한 후, 내보내기를 authAPI에서 refreshAPI로 변경했습니다.
인증 서비스 업데이트
src/api/service/auth-service/index.ts
authAPI에서 baseAPI/refreshAPI로 전환하고, 모든 요청에 withCredentials: true 옵션을 추가했습니다.
Auth Provider 단순화
src/providers/provider-auth/index.tsx
마운트 시 자동 갱신 로직을 제거하고, AuthContext에 setIsAuthenticated setter를 노출했습니다.
프록시 미들웨어 토큰 갱신
src/proxy.ts
비동기 함수로 변환하고, 액세스 토큰이 없지만 갱신 토큰이 있을 때 refresh API를 호출하는 제어된 갱신 흐름을 추가했습니다.
응답 타입 확장
src/types/service/auth.ts
LoginResponse 인터페이스에 expiresAt 필드를 추가했습니다.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested labels

Ready For Review!

Suggested reviewers

  • wooktori

Poem

🐰 토큰을 분리하니 명확하네,
갱신의 흐름이 이제 제어되고,
자동에서 의도로 변하며,
프록시가 현명하게 지키는 문,
인증의 길은 더욱 깔끔해졌네! 🔐

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning PR 설명이 변경사항을 상세히 기술하고 있으나, 필수 섹션인 테스트 방법과 체크리스트의 모든 항목이 미완료 상태입니다. 관련 이슈도 연결되지 않았습니다. 테스트 검증 방법 중 실제 수행한 항목을 체크하고, 관련 이슈 번호를 명시하며, 체크리스트의 필요한 항목을 완료해주세요.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed PR 제목이 주요 변경사항을 명확하게 요약하고 있습니다. Axios 인스턴스 수정 및 refresh 주체 변경이라는 핵심 내용이 잘 반영되어 있습니다.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch chiyoung-refactor/auth

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@github-actions
Copy link

github-actions bot commented Feb 21, 2026

🎭 Playwright Report

E2E Test가 성공적으로 완료되었습니다.

Test 요약 내용을 확인해주세요.

Status Build Log Updated (UTC)
✅ Ready View Build 2026-02-21 13:05:49

📊 Test Summary

  • ✅ Passed: 3
  • ❌ Failed: 0
  • ⏱️ Duration: 40.6s

📜 Test Details

✅ Passed Tests (3)
  • profile.test.ts (3)
    • [chromium] 존재하지 않는 프로필 페이지로 접속 시 404 redirect 되는 지 테스트
    • [firefox] 존재하지 않는 프로필 페이지로 접속 시 404 redirect 되는 지 테스트
    • [webkit] 존재하지 않는 프로필 페이지로 접속 시 404 redirect 되는 지 테스트

@github-actions
Copy link

github-actions bot commented Feb 21, 2026

🎨 Storybook Report

변경 사항이 없습니다

모든 Story가 이전 빌드와 동일합니다.

Status Storybook Build Log Updated (UTC)
✅ Unchanged View Storybook View Build 2026-02-21 13:04:37

@github-actions
Copy link

github-actions bot commented Feb 21, 2026

🚀 PR Preview Report

Build가 성공적으로 완료되었습니다.

Preview에서 변경사항을 확인하세요.

Status Preview Build Log Updated (UTC)
✅ Ready Visit Preview View Logs 2026-02-21 13:05:24

@github-actions
Copy link

github-actions bot commented Feb 21, 2026

📊 Coverage Report

Status Build Log Updated (UTC)
✅ Ready View Build 2026-02-21 13:04:22

📉 #388main에 병합하면 coverage가 0.21% 감소합니다.

Coverage 요약

@@             Coverage Diff             @@
##             main     #388       +/-   ##
===========================================
- Coverage   35.68%   35.47%    -0.21%     
===========================================
  Files         262      262         0     
  Lines       12140    12143        +3     
  Branches      477      468        -9     
===========================================
- Hits         4332     4308       -24     
+ Misses       7808     7835       +27     

영향받은 파일

파일 Coverage 변화
/home/runner/work/WeGo_FrontEnd/WeGo_FrontEnd/src/api/core/refresh/index.ts 54.05% (+54.05%) ⬆️
/home/runner/work/WeGo_FrontEnd/WeGo_FrontEnd/src/api/service/auth-service/index.ts 66.66% (-1.85%) ⬇️
/home/runner/work/WeGo_FrontEnd/WeGo_FrontEnd/src/mock/service/auth/auth-utils.ts 27.86% (-0.47%) ⬇️
/home/runner/work/WeGo_FrontEnd/WeGo_FrontEnd/src/providers/provider-auth/index.tsx 100.00% (+15.39%) ⬆️

@Chiman2937
Copy link
Member Author

@coderabbitai review

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 21, 2026

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link
Contributor

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/api/core/refresh/index.ts (1)

13-26: ⚠️ Potential issue | 🔴 Critical

미들웨어 컨텍스트에서 next/headers cookies() 사용 불가 - 아키텍처 재설계 필요

next/headerscookies() API는 Server Components, Route Handlers, Server Actions 전용으로 설계되었으며, 미들웨어 컨텍스트에서는 작동하지 않습니다. 미들웨어는 별도의 런타임(종종 Edge)에서 실행되어 AsyncLocalStorage를 통한 요청 컨텍스트가 전파되지 않기 때문입니다.

현재 코드 흐름:

  • proxy.ts 미들웨어에서 API.authService.refresh() 호출 (line 22)
  • refresh/index.ts의 axios 인터셉터에서 next/headerscookies() 호출 시도 (line 17-18)
  • 미들웨어 컨텍스트에서 AsyncLocalStorage가 전파되지 않음
  • cookieStore.get('refreshToken')undefined 반환
  • 리프레시 요청이 쿠키 없이 전송되어 proxy.ts line 30의 catch 블록에서 조용히 실패

해결 방안:

  • 미들웨어에서 이미 접근 가능한 refreshToken을 axios 인터셉터에 전달하거나
  • 미들웨어 내에서 직접 새 accessToken을 획득한 후 refresh API 호출을 제거하거나
  • axios 인터셉터를 클라이언트 환경에서만 작동하도록 제한 (isServer 조건일 때 쿠키 주입 제거)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/api/core/refresh/index.ts` around lines 13 - 26, The interceptor
refreshInstance.interceptors.request.use is trying to call next/headers
cookies() in a middleware context where AsyncLocalStorage isn't available,
causing cookieStore.get('refreshToken') to be undefined; fix by removing
server-side cookies() usage in the interceptor and instead have the middleware
pass the refresh token into the request (e.g., set a header like X-Refresh-Token
on the axios config in proxy.ts when calling API.authService.refresh()), or
alternatively perform the refresh entirely inside the middleware (call the
refresh endpoint from proxy.ts and set the new access token there) or scope the
interceptor to client-only (remove the isServer branch and only inject cookies
in client runtime). Ensure the change targets
refreshInstance.interceptors.request.use and the proxy.ts call site
(API.authService.refresh) so the refreshToken is provided from middleware rather
than calling cookies() inside the interceptor.
🧹 Nitpick comments (4)
src/proxy.ts (2)

22-24: 불필요한 중간 변수 data

const data = res;는 역할 없이 별칭만 추가합니다. res를 직접 사용하거나, 애초에 변수명을 data로 선언하면 됩니다.

♻️ 제안 수정
-     const res = await API.authService.refresh();
-     const data = res;
-     hasValidToken = true;
-     response.cookies.set('accessToken', data.accessToken, {
-       httpOnly: false,
-       maxAge: data.expiresIn,
+     const data = await API.authService.refresh();
+     hasValidToken = true;
+     response.cookies.set('accessToken', data.accessToken, {
+       httpOnly: false,
+       maxAge: data.expiresIn,
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/proxy.ts` around lines 22 - 24, The temporary alias const data = res is
redundant; update the API.authService.refresh() handling in this block (where
res, data, and hasValidToken are used) to remove the unnecessary data
variable—either use res directly in subsequent logic or rename the original
declaration to data (e.g., const data = await API.authService.refresh()) and
eliminate the extra assignment—so that only one variable (res or data) holds the
response before setting hasValidToken = true.

30-32: 리프레시 실패 시 에러 무음 처리 — 관찰 가능성 부재

catch 블록은 네트워크 타임아웃, 서버 오류 등의 실패 원인을 모두 숨깁니다. 적어도 console.error 또는 구조화된 로그를 남겨 운영 환경에서 추적이 가능하도록 하는 것을 권장합니다.

📋 제안 수정
    } catch (err) {
      hasValidToken = false;
+     console.error('[proxy] token refresh failed:', err);
    }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/proxy.ts` around lines 30 - 32, The empty catch that sets hasValidToken =
false swallows the refresh error; update the catch to capture the exception (e)
and log it (e.g., console.error or the app logger) before setting hasValidToken
= false so failures like timeouts or server errors are observable; locate the
try/catch around hasValidToken assignment in proxy.ts and replace the silent
catch with a logged error including contextual info (token refresh attempt and
error) so operators can trace issues.
src/providers/provider-auth/index.tsx (1)

4-6: setIsAuthenticated 컨텍스트 노출 — 의도적 설계인지 확인 필요

setIsAuthenticated를 컨텍스트로 외부에 노출하면 로그인·로그아웃·리프레시 흐름을 우회하여 임의의 하위 컴포넌트에서 인증 상태를 직접 변경할 수 있습니다. 현재 설계가 의도된 것이라면 최소한 사용 가이드를 주석으로 남기는 것이 좋습니다. 의도하지 않은 오용을 방지하려면 setIsAuthenticated 대신 login() / logout() 같은 명시적 액션 함수를 노출하는 방식을 권장합니다.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/providers/provider-auth/index.tsx` around lines 4 - 6, The context
currently exposes setIsAuthenticated which allows arbitrary components to mutate
auth state; change the context API to expose only isAuthenticated plus explicit
actions (e.g., login(), logout(), refreshAuth()/checkAuth()) instead of
setIsAuthenticated, update the provider implementation to keep internal state
via setIsAuthenticated but only call it from those action functions, and update
all consumers to call login()/logout() rather than calling setIsAuthenticated
directly; if exposing setIsAuthenticated was intentional, add a clear comment in
the context/type declaration documenting the intended usage and risks.
src/api/service/auth-service/index.ts (1)

38-40: refreshAPI 호출 시 withCredentials: true 중복

refreshInstance는 이미 인스턴스 수준에서 withCredentials: true로 생성되어 있으므로(src/api/core/refresh/index.ts 10번째 줄), 요청별로 다시 전달하는 것은 불필요합니다.

♻️ 제안 수정
-    const data = await refreshAPI.post<RefreshResponse>('/api/v1/auth/refresh', null, { withCredentials: true });
+    const data = await refreshAPI.post<RefreshResponse>('/api/v1/auth/refresh', null);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/api/service/auth-service/index.ts` around lines 38 - 40, The request to
refresh tokens redundantly passes { withCredentials: true } even though the
axios instance refreshInstance (used as refreshAPI) already sets withCredentials
at instance level; update the call in auth-service (the
refreshAPI.post<RefreshResponse> invocation) to remove the per-request options
object so it simply calls
refreshAPI.post<RefreshResponse>('/api/v1/auth/refresh', null), relying on the
refreshInstance configuration.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/proxy.ts`:
- Around line 25-29: The cookie domain is hardcoded in the response.cookies.set
call for 'accessToken' and missing the secure flag; change
response.cookies.set(...) to read the domain from an environment variable (e.g.,
process.env.COOKIE_DOMAIN or fallback to undefined) instead of 'wego.monster',
and add secure: true to the options (or compute secure based on NODE_ENV/HTTPS
detection if you need local HTTP support), keeping httpOnly, maxAge:
data.expiresIn, and the same cookie name ('accessToken').
- Around line 20-38: The refresh flow sets the accessToken on the local response
via response.cookies.set(...) but then returns a new NextResponse.redirect(...)
which drops that Set-Cookie header; to fix, create the redirect response (e.g.,
const redirectRes = NextResponse.redirect(new URL('/', request.url))) and copy
or re-set the same cookie on that redirect response before returning it,
preserving the cookie attributes (httpOnly, maxAge/expiresIn, domain) so the
browser receives accessToken when redirected; update the branch handling
isPublic && hasValidToken to return the modified redirect response instead of
the original response.

---

Outside diff comments:
In `@src/api/core/refresh/index.ts`:
- Around line 13-26: The interceptor refreshInstance.interceptors.request.use is
trying to call next/headers cookies() in a middleware context where
AsyncLocalStorage isn't available, causing cookieStore.get('refreshToken') to be
undefined; fix by removing server-side cookies() usage in the interceptor and
instead have the middleware pass the refresh token into the request (e.g., set a
header like X-Refresh-Token on the axios config in proxy.ts when calling
API.authService.refresh()), or alternatively perform the refresh entirely inside
the middleware (call the refresh endpoint from proxy.ts and set the new access
token there) or scope the interceptor to client-only (remove the isServer branch
and only inject cookies in client runtime). Ensure the change targets
refreshInstance.interceptors.request.use and the proxy.ts call site
(API.authService.refresh) so the refreshToken is provided from middleware rather
than calling cookies() inside the interceptor.

---

Nitpick comments:
In `@src/api/service/auth-service/index.ts`:
- Around line 38-40: The request to refresh tokens redundantly passes {
withCredentials: true } even though the axios instance refreshInstance (used as
refreshAPI) already sets withCredentials at instance level; update the call in
auth-service (the refreshAPI.post<RefreshResponse> invocation) to remove the
per-request options object so it simply calls
refreshAPI.post<RefreshResponse>('/api/v1/auth/refresh', null), relying on the
refreshInstance configuration.

In `@src/providers/provider-auth/index.tsx`:
- Around line 4-6: The context currently exposes setIsAuthenticated which allows
arbitrary components to mutate auth state; change the context API to expose only
isAuthenticated plus explicit actions (e.g., login(), logout(),
refreshAuth()/checkAuth()) instead of setIsAuthenticated, update the provider
implementation to keep internal state via setIsAuthenticated but only call it
from those action functions, and update all consumers to call login()/logout()
rather than calling setIsAuthenticated directly; if exposing setIsAuthenticated
was intentional, add a clear comment in the context/type declaration documenting
the intended usage and risks.

In `@src/proxy.ts`:
- Around line 22-24: The temporary alias const data = res is redundant; update
the API.authService.refresh() handling in this block (where res, data, and
hasValidToken are used) to remove the unnecessary data variable—either use res
directly in subsequent logic or rename the original declaration to data (e.g.,
const data = await API.authService.refresh()) and eliminate the extra
assignment—so that only one variable (res or data) holds the response before
setting hasValidToken = true.
- Around line 30-32: The empty catch that sets hasValidToken = false swallows
the refresh error; update the catch to capture the exception (e) and log it
(e.g., console.error or the app logger) before setting hasValidToken = false so
failures like timeouts or server errors are observable; locate the try/catch
around hasValidToken assignment in proxy.ts and replace the silent catch with a
logged error including contextual info (token refresh attempt and error) so
operators can trace issues.

@Chiman2937 Chiman2937 merged commit c15a0b4 into main Feb 21, 2026
7 checks passed
@Chiman2937 Chiman2937 deleted the chiyoung-refactor/auth branch February 21, 2026 13:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant