Skip to content

Conversation

six-standard
Copy link
Member

@six-standard six-standard commented Mar 6, 2025

image

원래 사용되던 NGINX 기본 오류 페이지 대신 사용할 커스텀 오류 페이지를 퍼블리싱하였습니다.
NextJS SSG를 사용하였으며, 빌드 후 /server/app 경로에서 생성되는 error.html 파일을 이용하면 됩니다.

Summary by CodeRabbit

  • 버그 수정
    • 인증 오류 처리 방식을 개선하여, 권한이 없는 경우 사용자가 홈 화면으로 원활하게 리디렉션됩니다.
    • 로그아웃 프로세스에 데이터 재검증 단계를 추가해 안정적인 세션 전환을 지원합니다.
  • 새로운 기능
    • 예기치 않은 오류 발생 시 사용자에게 직관적이고 반응형인 오류 페이지가 표시됩니다.

Copy link

coderabbitai bot commented Mar 6, 2025

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

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.

Walkthrough

이 변경사항은 여러 컴포넌트 및 유틸리티에서 오류 처리와 쿼리 클라이언트 사용 방식을 수정합니다. 주요 내용으로는 API 요청 모듈에서 403 대신 401 상태코드를 처리하도록 변경되고, 로그인 및 로그아웃 관련 컴포넌트에서 쿼리 클라이언트 사용 방식이 업데이트됩니다. 또한 쿼리의 가비지 컬렉션 시간 조정, 사용자 리다이렉션을 위한 새로운 revalidate 함수 도입, 오류 표시에 쓰이는 HTML 템플릿 추가, 그리고 Sentry 관련 의존성 추가가 포함되어 있습니다.

Changes

파일 경로 변경 요약
src/apis/instance.request.ts 403 대신 401 상태코드를 확인하여, location이 설정된 경우 '/'로 리다이렉트하도록 오류 처리 로직 수정 및 관련 주석 제거.
src/app/(with-tracker)/(login)/Content.tsx useQueryClient 훅 삭제 및 관련 변수 제거로, onSuccess에서 query cache 클리어 호출 삭제.
src/components/auth-required/header/index.tsx
src/components/auth-required/main/Section/index.tsx
헤더와 메인 섹션 컴포넌트에서 useQueryClient 대신 getQueryClient 사용, logout 시 revalidate 함수 호출 추가 및 사용자 프로필 쿼리에 enabled 옵션 추가, username 검증 로직 제거.
src/utils/queryUtil.ts GC_TIME 상수를 1000ms에서 20분(1200000ms)으로 변경.
src/utils/revalidateUtil.ts 비동기 revalidate 함수 추가: revalidatePath 호출 후 '/'로 리다이렉션 수행.
error.html 오류 메시지 표시용 HTML 템플릿 추가, 반응형 CSS 스타일 적용 및 다크 테마 구성.
package.json 새로운 의존성 @sentry/core (버전 ^9.4.0) 추가.

Sequence Diagram(s)

sequenceDiagram
    participant U as 사용자
    participant H as 헤더 컴포넌트
    participant R as revalidate()
    participant QC as QueryClient
    participant Router as 라우터

    U->>H: 로그아웃 버튼 클릭
    H->>H: 로그아웃 뮤테이션 트리거
    H->>R: 비동기 revalidate() 호출
    R->>R: '/'에 대한 revalidatePath 실행
    R->>Router: '/'로 리다이렉션 수행
    H->>QC: 쿼리 캐시 삭제
    H->>Router: 라우터 경로 대체('/')
Loading
sequenceDiagram
    participant U as 사용자
    participant API as API 인스턴스
    participant B as 브라우저

    U->>API: API 요청 전송
    API-->>API: 응답 상태(401) 확인
    API->>B: location이 존재할 경우 '/'로 리다이렉트
Loading

Possibly related PRs

Suggested labels

bug

Suggested reviewers

  • HA0N1
  • Nuung

Poem

나는 작은 토끼, 코드 숲을 달리네,
401의 문턱을 넘어 새 길을 찾았네.
revalidate의 빛으로 길을 밝혀,
쿼리 클라이언트도 한 곳에 모으네.
오류의 그림자 사라지고,
행복한 코드가 피어나는 날,
당근처럼 달콤한 변경을 노래하네!


🪧 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • 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 generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

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 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.

Copy link

@six-standard six-standard self-assigned this Mar 6, 2025
@six-standard six-standard added the enhancement New feature or request label Mar 6, 2025
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

🧹 Nitpick comments (2)
src/app/error/page.tsx (2)

8-8: Image 컴포넌트의 속성을 최신 Next.js 권장사항에 맞게 수정하세요.

Next.js 13 이상에서는 layout="fill" 대신 fill={true}를 사용하는 것이 권장됩니다.

-            <Image layout="fill" src={'/favicon.png'} alt="" />
+            <Image fill src={'/favicon.png'} alt="Velog Dashboard 로고" />

16-18: 더 구체적인 에러 메시지나 사용자 안내 추가를 고려해보세요.

현재는 일반적인 에러 메시지만 표시하고 있습니다. 사용자에게 새로고침을 시도하거나 홈으로 돌아갈 수 있는 버튼 등을 제공하면 더 나은 사용자 경험을 제공할 수 있습니다.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0a45831 and b49b5d3.

📒 Files selected for processing (7)
  • src/apis/instance.request.ts (1 hunks)
  • src/app/(with-tracker)/(login)/Content.tsx (1 hunks)
  • src/app/error/page.tsx (1 hunks)
  • src/components/auth-required/header/index.tsx (2 hunks)
  • src/components/auth-required/main/Section/index.tsx (1 hunks)
  • src/utils/queryUtil.ts (1 hunks)
  • src/utils/revalidateUtil.ts (1 hunks)
🔇 Additional comments (11)
src/utils/queryUtil.ts (1)

6-6: GC_TIME 값 변경에 대한 영향 고려가 필요합니다.

GC_TIME 값이 1초에서 20분으로 크게 증가되었습니다. 이는 쿼리 캐시가 메모리에 유지되는 시간을 대폭 늘리는 변경사항입니다.

이 변경으로 사용자 경험이 개선될 수 있지만(데이터 재요청 감소), 장시간 사용 시 메모리 사용량이 증가할 수 있습니다. 해당 값이 애플리케이션의 성능 요구사항에 적합한지 확인해 보세요.

src/app/(with-tracker)/(login)/Content.tsx (1)

6-6: 로그인 성공 후 쿼리 캐시 초기화 로직이 제거되었습니다.

useQueryClient import와 client.clear() 호출이 제거되었습니다. 이전 코드에서는 로그인 성공 후 캐시를 초기화했지만, 현재는 그 로직이 없습니다.

이 변경사항이 의도적인지 확인하고, 다른 부분(예: header의 logout 함수)과의 일관성이 유지되는지 검토해보세요. 로그인 시점에 캐시를 유지하는 것이 애플리케이션의 데이터 흐름 관점에서 정확한지 확인이 필요합니다.

src/app/error/page.tsx (1)

1-22: 에러 페이지 구현이 잘 되었습니다.

에러 처리 페이지가 깔끔하게 구현되었습니다. 디자인이 애플리케이션의 전체적인 스타일과 일관성 있게 유지되고 있으며, 반응형 디자인도 적절히 적용되어 있습니다.

src/components/auth-required/header/index.tsx (3)

12-13: revalidate 유틸리티 추가가 적절합니다.

revalidate 유틸리티를 가져와서 로그아웃 처리 과정에 적용한 것은 좋은 접근입니다.


42-46: 비동기 처리 개선이 잘 되었습니다.

로그아웃 시 revalidate 함수를 비동기로 처리하고, 완료 후 캐시 클리어 및 리다이렉트를 수행하도록 개선한 점이 좋습니다. 이는 로그아웃 과정에서 데이터 상태 관리를 더 안정적으로 만듭니다.


52-55: 쿼리 최적화가 잘 구현되었습니다.

enabled 속성을 사용하여 캐시된 데이터가 있을 때만 쿼리를 실행하도록 최적화한 것은 좋은 접근법입니다. 코드 주석도 명확하게 작성되어 이해하기 쉽습니다.

src/apis/instance.request.ts (1)

78-78: 상태 코드 검증 변경이 적절합니다.

401(Unauthorized) 상태 코드로 변경하여 인증 관련 오류를 더 명확하게 처리하고 있습니다. 이전에는 403(Forbidden)을 체크하고 있었으나, 인증 실패 시 401이 더 의미적으로 정확합니다.

src/utils/revalidateUtil.ts (1)

1-9: 'use server' 지시문과 revalidate 함수 구현이 적절합니다.

서버 컴포넌트에서 사용하기 위한 'use server' 지시문과 함께 경로 재검증 및 리다이렉션 로직이 잘 구현되어 있습니다. 이 함수는 인증 관련 작업 후 페이지를 새로고침하는 데 유용하게 사용될 것입니다.

src/components/auth-required/main/Section/index.tsx (3)

9-9: useQueryClient에서 getQueryClient로의 변경이 적절합니다.

리액트 훅 대신 유틸리티 함수를 사용하여 쿼리 클라이언트에 접근하도록 변경되었습니다.


15-17: 사용자 이름 유효성 검사 누락 가능성이 있습니다.

이전 코드에서는 username이 없을 경우 에러를 던지는 유효성 검사가 있었을 것으로 추정되나, 현재 구현에서는 이 검사가 제거되었습니다. username이 undefined일 경우 후속 코드에서 문제가 발생할 수 있습니다.

username이 undefined인 경우에 대한 처리를 추가하는 것이 좋을 것 같습니다. 다음과 같은 방식으로 구현할 수 있습니다:

  const username = (
    getQueryClient().getQueryData([PATHS.ME]) as Partial<UserDto>
  )?.username;

+ if (!username) {
+   // 적절한 에러 처리 또는 기본값 설정
+   console.error('사용자 이름을 찾을 수 없습니다.');
+ }

  const url = `${env.VELOG_URL}/@${username}/${p.slug}`;

19-19: URL 구성 로직이 개선되었습니다.

URL 생성 로직이 간소화되어 가독성이 향상되었습니다.

Copy link
Member

@Nuung Nuung left a comment

Choose a reason for hiding this comment

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

에고 너무 고생많으셨고 너무 좋아요

허나 기준님도 아시다시피 SSG 로 해당 페이지를 뽑아서 L7 LB 역할해주는 서버에 따로 배포하는 로직은 굉장히 굳이 있어야 하나? 싶은 방법이에요~

next 서버 runtime 에서 status 판단 후 해당 페이지를 렌더링해주는 로직에는 동의해요

저희 기존 배포는 CD 가 docker hub 에 image 를 올려주고
서버에 따로 붙어서 해당 image 를 다시 pull 해서 각 서버 instance 에서 직접 build 하는 방식이라서요

허나 이렇게 ssg 가 끼는 순간 이미지를 "만드는 로직" 에도 해당 ssg 러닝이 필요하며
그리고 해당 static file 만 L7 LB 서버에 따로 업로드하는 로직히 핊요하며
nginx 에는 또 reload 를 해줘야 해요

=======

그래서 자체적으로 next 에서 뱉는 4xx 5xx 는 그대로 가되
L7 LB 역할을 하는 서버에는 단순 html 만 올릴거에요

그래서 "next 라는 것과 완벽하게 무관한" static file 이 필요해요

@six-standard
Copy link
Member Author

에고 너무 고생많으셨고 너무 좋아요

허나 기준님도 아시다시피 SSG 로 해당 페이지를 뽑아서 L7 LB 역할해주는 서버에 따로 배포하는 로직은 굉장히 굳이 있어야 하나? 싶은 방법이에요~

next 서버 runtime 에서 status 판단 후 해당 페이지를 렌더링해주는 로직에는 동의해요

저희 기존 배포는 CD 가 docker hub 에 image 를 올려주고 서버에 따로 붙어서 해당 image 를 다시 pull 해서 각 서버 instance 에서 직접 build 하는 방식이라서요

허나 이렇게 ssg 가 끼는 순간 이미지를 "만드는 로직" 에도 해당 ssg 러닝이 필요하며 그리고 해당 static file 만 L7 LB 서버에 따로 업로드하는 로직히 핊요하며 nginx 에는 또 reload 를 해줘야 해요

=======

그래서 자체적으로 next 에서 뱉는 4xx 5xx 는 그대로 가되 L7 LB 역할을 하는 서버에는 단순 html 만 올릴거에요

그래서 "next 라는 것과 완벽하게 무관한" static file 이 필요해요

이해했습니다~
사실 개발의 용이성 때문에 NextJS SSG를 선택했긴 하지만, 굳이 빌드 결과물에서 파일을 뺴서 NGINX에 업로드하는 로직이 필요할 거라곤 생각해보지 못했네요.

@Nuung
Copy link
Member

Nuung commented Mar 6, 2025

@six-standard 해당 PR 은 그래서 어떻게 하는게 좋을까요? 기준님이 마지막 결론 내려주세요 :)

@six-standard
Copy link
Member Author

@six-standard 해당 PR 은 그래서 어떻게 하는게 좋을까요? 기준님이 마지막 결론 내려주세요 :)

그냥 단순 HTML 파일로 새로 만들어서 프로젝트 root 경로에 추가해두면 될 것 같다고 생각합니다!
괜찮을까요?

@six-standard six-standard requested a review from Nuung March 7, 2025 00:44
@six-standard six-standard changed the base branch from main to dev March 7, 2025 00: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: 0

🧹 Nitpick comments (1)
package.json (1)

18-18: 새로운 Sentry 의존성 추가 확인
추가된 "@sentry/core": "^9.4.0"는 에러 트래킹 및 성능 모니터링을 강화하기 위한 의도로 보입니다. 다만, 이미 "@sentry/nextjs": "^8.47.0"가 포함되어 있으므로, 두 패키지가 서로 중복되거나 충돌하는 이슈가 발생하지 않는지 확인 부탁드립니다.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b49b5d3 and 828e479.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (2)
  • error.html (1 hunks)
  • package.json (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • error.html

Copy link

@Jihyun3478 Jihyun3478 left a comment

Choose a reason for hiding this comment

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

좋았던 점

  • 사용자 관점에서 개선되어지는 부분들이 많아 너무 좋은 것 같아요!
    • NGINX 기본 오류 페이지 대신 커스텀 오류 페이지가 띄워지는 부분
    • 권한이 없는 경우 홈 화면으로 리다이렉션 되는 부분

PS. 이전 PR과 동일한 부분이 많아 답변은 거기서 해주시면 감사하겠습니다:)

@Nuung
Copy link
Member

Nuung commented Mar 7, 2025

@six-standard 해당 PR 은 그래서 어떻게 하는게 좋을까요? 기준님이 마지막 결론 내려주세요 :)

그냥 단순 HTML 파일로 새로 만들어서 프로젝트 root 경로에 추가해두면 될 것 같다고 생각합니다! 괜찮을까요?

좋습니다! 그렇게 가시죠! 그런 다음에 해당 PR 종결하시죠!!

@six-standard
Copy link
Member Author

@six-standard 해당 PR 은 그래서 어떻게 하는게 좋을까요? 기준님이 마지막 결론 내려주세요 :)

그냥 단순 HTML 파일로 새로 만들어서 프로젝트 root 경로에 추가해두면 될 것 같다고 생각합니다! 괜찮을까요?

좋습니다! 그렇게 가시죠! 그런 다음에 해당 PR 종결하시죠!!

파일 추가했습니다!

Copy link

@cheonHwi cheonHwi left a comment

Choose a reason for hiding this comment

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

좋았던 점

  • 기존에 없던 오류에 대한 페이지가 추가된 것.
  • 권한이 없는 경우에 메인으로 리다이렉트 되는 부분

저도 처음에 보면서 오류 페이지는 정적 파일을 nginx에서 직접 보여주는 방향도 괜찮지 않을까 싶었는데 그런 방향으로 진행되는거 같아서 좋은 것 같습니다~!

@six-standard six-standard requested a review from Nuung March 8, 2025 02:20
@six-standard six-standard merged commit 6a02bf2 into dev Mar 8, 2025
1 check passed
@six-standard six-standard deleted the feature/500-error-page branch March 9, 2025 15:07
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.

4 participants