Skip to content

Conversation

@sgoldenbird
Copy link
Contributor

@sgoldenbird sgoldenbird commented Aug 7, 2025

👻 관련 이슈 번호

  • none

👻 요약

사용자 인증 관련 로직을 개선하여 불필요한 네트워크 요청을 줄이고, 401 에러(인증 실패) 처리 과정을 효율적으로 개선

👻 주요 변경 사항

  • API 클라이언트의 beforeErrorHook에 401 에러를 처리하는 로직을 추가했습니다.

    • 보호된 페이지에서 401 에러 발생 시, TanStack Query 캐시를 무효화하고 세션 만료 에러 코드와 함께 메인 페이지로 리디렉션합니다.
    • 보호되지 않은 페이지에서는 페이지를 새로고침하여 상태를 동기화합니다.
    • 기존의 중복된 clearUser() 호출을 제거하여 코드를 정리했습니다.
  • src/domain/Auth/hooks/useUser.ts 수정

    • useQuery 옵션에 refetchOnWindowFocus: true와 refetchOnReconnect: true를 추가하여, 브라우저 탭을 다시 포커스하거나 네트워크 연결이 재개될 때 자동으로 사용자 정보를 다시 가져오도록 했습니다.
  • maxAge 옵션의 테스트용 주석을 정리하고, 최종 maxAge가 60 * 60으로 설정되도록 변경했습니다.

  • kakao Oauth gif 추가

👻 체크리스트

  • Assignees에 본인을 등록했나요?
  • 라벨을 사이드 탭에서 등록했나요?
  • PR은 사이드 탭 Projects를 등록 하지마세요.
  • PR은 Milestone을 등록 하지마세요.
  • PR을 보내는 브랜치가 올바른지 확인했나요?
  • 팀원들이 리뷰하기 쉽도록 설명을 자세하게 작성했나요?
  • 변경사항을 충분히 테스트 했나요?
  • 컨벤션에 맞게 구현했나요?

📷 UI 변경 사항

👻 문제 사항

👻 논의 사항

👻 기타 참고 사항

Summary by CodeRabbit

  • Refactor
    • 401 응답 처리 시 로그인 상태에 따른 세션 만료 처리 및 리다이렉션 로직이 개선되었습니다.
    • 보호되지 않은 페이지에서 401 오류 발생 시 로그를 기록하고 페이지를 새로고침하도록 처리하였습니다.
    • API 요청 시 동일 출처에 한해 쿠키 및 인증 정보를 전송하도록 설정이 변경되었습니다.
    • 토큰 갱신 요청 시 리프레시 토큰을 쿠키로 함께 전송하도록 개선하였습니다.
    • 사용자 데이터 강제 재요청을 위한 초기화 컴포넌트 수정 및 자동 재요청 설정이 추가되었습니다.
    • 사용자 데이터 쿼리의 자동 재요청 조건이 윈도우 포커스 및 네트워크 재연결 시로 변경되었습니다.
    • 액세스 토큰 쿠키의 만료 시간이 10초에서 1시간으로 정상 복구되었습니다.

@sgoldenbird sgoldenbird self-assigned this Aug 7, 2025
@sgoldenbird sgoldenbird added the fix label Aug 7, 2025
@sgoldenbird sgoldenbird linked an issue Aug 7, 2025 that may be closed by this pull request
7 tasks
@coderabbitai
Copy link

coderabbitai bot commented Aug 7, 2025

Walkthrough

401 상태 코드와 보호된 페이지 여부를 확인하는 조건문이 단순화되었습니다. 이제 isCurrentlyOnProtectedPage 불리언만을 사용하여 분기하며, 401 에러가 비보호 페이지에서 발생할 때는 세션 만료 메시지를 로그로 남기고 페이지를 새로고침합니다. queryClient.invalidateQueries 호출에 캐시 무효화임을 명시하는 주석이 추가되었습니다. 또한 apiClientcredentials: 'same-origin' 옵션이 추가되어 동일 출처 요청에만 인증 정보를 포함하도록 변경되었습니다. 미들웨어에서는 토큰 갱신 요청 시 refreshToken 쿠키를 Cookie 헤더에 포함하도록 수정하고, 응답 본문을 텍스트로 읽어 새 NextResponse 객체를 생성하여 인증 쿠키를 설정합니다. AuthInitializer 컴포넌트는 마운트 시 refetch()를 호출하도록 변경되었고, useUser 훅은 staleTime 대신 refetchOnWindowFocusrefetchOnReconnect 옵션을 추가하여 사용자 데이터를 자동 갱신하도록 개선되었습니다.

Changes

Cohort / File(s) Change Summary
401 에러 처리 조건 단순화 및 세션 만료 처리 추가
src/shared/libs/formatErrorResponseHooks.ts
401 상태와 보호 페이지 여부를 확인하는 조건문을 단순화하고, 비보호 페이지에서 401 발생 시 로그 출력 후 페이지 새로고침 처리. 캐시 무효화 주석 추가.
apiClient 인증 정보 설정 추가
src/shared/libs/apiClient.ts
credentials: 'same-origin' 옵션을 추가하여 동일 출처 요청에만 인증 정보를 포함하도록 설정함.
미들웨어 토큰 갱신 요청 헤더 및 응답 처리 수정
src/middleware.ts
토큰 갱신 시 refreshToken 쿠키를 Cookie 헤더에 포함하고, 응답 본문을 텍스트로 읽어 새 NextResponse 객체를 생성하여 인증 쿠키를 설정하도록 변경함.
AuthInitializer 컴포넌트 사용자 데이터 강제 재요청 추가
src/app/_components/AuthInitializer.tsx
useUser 훅에서 refetch를 추출하고, 컴포넌트 마운트 시 refetch()를 호출하도록 useEffect 훅 추가.
useUser 훅 쿼리 옵션 변경
src/domain/Auth/hooks/useUser.ts
staleTime 옵션 제거, refetchOnWindowFocusrefetchOnReconnect 옵션 추가로 사용자 데이터 자동 갱신 활성화.
setAuthCookies 주석 정리
src/domain/Auth/utils/setAuthCookies.ts
access token cookie maxAge 주석을 원래대로 복원, 실제 maxAge 값은 10초로 유지.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested reviewers

  • Yongmin0423
  • justhighway

Poem

깡충깡충 작은 토끼가 말해요,
401은 이제 더 간단해졌대요.
보호된 페이지만 살피고,
세션 만료면 새로고침 콕!
apiClient엔 쿠키를 담고,
미들웨어는 토큰 새로 고쳐,
사용자 데이터도 쭉쭉 갱신해요 🐇✨

Note

🔌 MCP (Model Context Protocol) integration is now available in Early Access!

Pro users can now connect to remote MCP servers under the Integrations page to get reviews and chat conversations that understand additional development context.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 65b1faa and 0318545.

📒 Files selected for processing (1)
  • src/domain/Auth/utils/setAuthCookies.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/domain/Auth/utils/setAuthCookies.ts
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/546/user-sync

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@github-actions
Copy link

github-actions bot commented Aug 7, 2025

✅ Preview Deployment Ready!

🔗 Preview URL: https://roam-ready-l8630wllg-yongmins-projects-bf5f7733.vercel.app
📝 Branch: feat/546/user-sync
💾 Commit: Fix: beforeErrorHook에 전역 상태 초기화 및 TanStack Query 캐시 무효화 로직 추가
🕐 Deployed at:


This preview will be automatically updated on new commits.

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: 0

🔭 Outside diff range comments (1)
src/shared/libs/formatErrorResponseHooks.ts (1)

26-36: 리다이렉트 직후 불필요한 로직 실행을 방지하기 위해 return을 추가하세요
window.location.href를 설정한 뒤에도 함수는 계속 실행됩니다(비동기 환경에서는 즉시 탐색이 보장되지 않음). 안전하게 종료하려면 리다이렉트 이후에 return으로 조기 종료해 주는 편이 좋습니다.

       window.location.href = redirectUrl.toString();
+      return error; // 리다이렉트 후 추가 로직 방지
🧹 Nitpick comments (2)
src/shared/libs/formatErrorResponseHooks.ts (2)

12-13: protectedPageRoutes는 함수 외부로 이동하여 재할당을 방지하세요
protectedPageRoutes는 불변 상수이므로, beforeErrorHook가 호출될 때마다 새 배열을 생성할 필요가 없습니다. 파일 상단(모듈 스코프)으로 옮기면 미세하지만 불필요한 메모리 할당을 줄일 수 있고 의도도 더 명확해집니다.


19-20: invalidateQueries 반환 Promise를 await로 명시적으로 처리하세요
queryClient.invalidateQueries는 Promise를 반환합니다. 뒤이어 즉시 리다이렉트가 발생할 수 있으므로, 캐시 무효화가 완료되기 전에 네트워크 이동이 일어나면 의도한 효과가 적용되지 않을 수 있습니다.

- queryClient.invalidateQueries({ queryKey: ['user', 'me'] }); // 캐시 무효화
+ await queryClient.invalidateQueries({ queryKey: ['user', 'me'] }); // 캐시 무효화
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ab9ec67 and 536bc1b.

📒 Files selected for processing (1)
  • src/shared/libs/formatErrorResponseHooks.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/shared/libs/formatErrorResponseHooks.ts (1)
src/shared/libs/queryClient.ts (1)
  • queryClient (14-24)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: vercel-preview

@github-actions
Copy link

github-actions bot commented Aug 7, 2025

✅ Preview Deployment Ready!

🔗 Preview URL: https://roam-ready-otbx3bfjd-yongmins-projects-bf5f7733.vercel.app
📝 Branch: feat/546/user-sync
💾 Commit: Fix: beforeErrorHook에 전역 상태 초기화 및 TanStack Query 캐시 무효화 로직 추가
🕐 Deployed at:


This preview will be automatically updated on new commits.

@github-actions
Copy link

github-actions bot commented Aug 7, 2025

✅ Preview Deployment Ready!

🔗 Preview URL: https://roam-ready-f6r0vgmmz-yongmins-projects-bf5f7733.vercel.app
📝 Branch: feat/546/user-sync
💾 Commit: Fix: beforeErrorHook에 전역 상태 초기화 및 TanStack Query 캐시 무효화 로직 추가
🕐 Deployed at:


This preview will be automatically updated on new commits.

@sgoldenbird sgoldenbird force-pushed the feat/546/user-sync branch 2 times, most recently from 5461670 to 5449e7b Compare August 7, 2025 03:45
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: 1

🧹 Nitpick comments (2)
src/domain/Auth/hooks/useUser.ts (2)

60-61: 네트워크 요청 빈도 증가에 대한 검토가 필요합니다.

refetchOnWindowFocusrefetchOnReconnect를 모두 true로 설정하면 사용자가 창을 전환하거나 네트워크가 재연결될 때마다 API 요청이 발생합니다. 이는 불필요한 네트워크 트래픽을 증가시킬 수 있습니다.

사용자 경험과 서버 부하를 고려하여 다음 중 하나를 검토해보세요:

  • staleTime을 적절한 값(예: 1분)으로 설정하여 불필요한 요청 방지
  • 또는 refetchOnWindowFocus만 활성화하고 refetchOnReconnect는 제거
  const queryResult = useQuery({
    queryKey: ['user', 'me'],
    queryFn: getMe,
    retry: 1,
+   staleTime: 1000 * 60, // 1분간 fresh 상태 유지
    refetchOnWindowFocus: true,
-   refetchOnReconnect: true,
  });

29-29: 문서가 실제 구현과 일치하지 않습니다.

29번 줄의 JSDoc에서 staleTime이 5분으로 설정된다고 명시되어 있지만, 실제 코드에서는 staleTime이 제거되었습니다.

- * @property {number} staleTime - 데이터를 'fresh' 상태로 유지하는 시간 (5분).
+ * @property {boolean} refetchOnWindowFocus - 윈도우 포커스 시 데이터를 자동으로 다시 가져올지 여부.
+ * @property {boolean} refetchOnReconnect - 네트워크 재연결 시 데이터를 자동으로 다시 가져올지 여부.
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5461670 and 5449e7b.

📒 Files selected for processing (5)
  • src/app/_components/AuthInitializer.tsx (2 hunks)
  • src/domain/Auth/hooks/useUser.ts (1 hunks)
  • src/middleware.ts (2 hunks)
  • src/shared/libs/apiClient.ts (1 hunks)
  • src/shared/libs/formatErrorResponseHooks.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/shared/libs/formatErrorResponseHooks.ts
  • src/shared/libs/apiClient.ts
  • src/middleware.ts
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/app/_components/AuthInitializer.tsx (1)
src/domain/Auth/hooks/useUser.ts (1)
  • useUser (52-81)

*/
export default function AuthInitializer() {
useUser();
const { refetch } = useUser(); // 쿼리 객체를 받아서
Copy link

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

초기화 로직이 명확해졌습니다.

refetch를 명시적으로 호출하여 앱 로드 시 사용자 데이터를 강제로 가져오는 로직이 명확해졌습니다. 이는 인증 상태 동기화를 보장하는 좋은 접근 방식입니다.

다만 useQuery는 기본적으로 컴포넌트 마운트 시에도 실행되므로, refetch() 호출이 중복 요청을 발생시킬 가능성이 있습니다.

중복 요청 여부를 확인하기 위해 다음 스크립트를 실행하여 useQuery의 기본 설정을 확인해보세요:

Also applies to: 17-20


🏁 Script executed:

#!/bin/bash
# useQuery 기본 동작 확인을 위해 관련 설정들을 찾아봅니다
rg -A 10 -B 5 "useQuery|QueryClient" --type ts --type tsx

Length of output: 87


tsx 파일 타입 필터가 인식되지 않아, 전체 파일을 대상으로 useQueryQueryClient를 다시 검색해주세요.


🏁 Script executed:

#!/bin/bash
# 전체 파일에서 useQuery 및 QueryClient 사용 위치를 확인합니다
rg -n -A5 -B5 "useQuery|QueryClient" .

Length of output: 33839


중복 네트워크 요청 방지 검토 필요

AuthInitializer.tsx에서 useUser 훅을 통해 { refetch }를 분해한 뒤, useEffect로 마운트 시 다시 refetch()를 호출하고 있습니다.
그러나 useUser 내부에는 다음과 같이 useQuery를 사용하고 있어:

  • 컴포넌트 마운트 시 기본적으로 getMe 요청을 자동 실행
  • staleTime 기본값(0)으로 마운트마다 재요청이 보장됨

따라서 useEffect에서 추가로 호출하는 refetch()는 불필요한 중복 요청을 유발할 수 있습니다.

수정 제안:

  • useEffect 내의 refetch() 호출 제거
  • 또는 staleTime/refetchOnMount 옵션을 조정해 의도한 동작만 발생하도록 변경

교정이 필요한 위치:

  • src/app/_components/AuthInitializer.tsx
    • 15번 줄: const { refetch } = useUser();
    • 17–20번 줄: useEffect(() => { refetch() }, [refetch])
🤖 Prompt for AI Agents
In src/app/_components/AuthInitializer.tsx around lines 15 to 20, the useEffect
hook calls refetch() on mount, causing redundant network requests because
useUser's underlying useQuery already fetches data on mount with staleTime 0. To
fix this, remove the useEffect block that calls refetch(), or alternatively
adjust the useUser hook's useQuery options by setting staleTime to a higher
value or refetchOnMount to false to prevent duplicate requests.

@github-actions
Copy link

github-actions bot commented Aug 8, 2025

✅ Preview Deployment Ready!

🔗 Preview URL: https://roam-ready-2woqm5ocj-yongmins-projects-bf5f7733.vercel.app
📝 Branch: feat/546/user-sync
💾 Commit: Fix: beforeErrorHook에 전역 상태 초기화 및 TanStack Query 캐시 무효화 로직 추가
🕐 Deployed at:


This preview will be automatically updated on new commits.

@sgoldenbird sgoldenbird merged commit de1e848 into main Aug 8, 2025
2 checks passed
@sgoldenbird sgoldenbird deleted the feat/546/user-sync branch August 8, 2025 07:19
@coderabbitai coderabbitai bot mentioned this pull request Aug 29, 2025
8 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Fix: 유저 정보 동기화 문제

2 participants