[FIX] 개발 환경 프록시 순환 참조 문제 해결 및 설정 개선#163
Conversation
Summary of ChangesHello @kanghaeun, 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! 이 Pull Request는 개발 환경에서 발생할 수 있는 Vite 프록시의 순환 참조 문제를 해결하고, 프록시 설정을 더욱 명확하게 개선하는 것을 목표로 합니다. API 기본 URL과 프록시 타겟을 별도의 환경 변수로 분리함으로써, 개발 서버가 API 요청을 올바르게 라우팅하고 잠재적인 설정 오류를 방지하여 보다 견고한 개발 환경을 제공합니다. Highlights
Using Gemini Code AssistThe 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
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 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
|
|
Note Other AI code review bot(s) detectedCodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review. WalkthroughUpdated multiple frontend API modules to build request URLs using the environment base URL (VITE_API_BASE_URL) instead of relative /api paths, and adjusted Vite proxy to use VITE_PROXY_TARGET. One file also renamed a local response variable. No changes to exported function signatures or error handling. Changes
Sequence Diagram(s)Estimated code review effort🎯 2 (Simple) | ⏱️ ~10 minutes Possibly related issues
Possibly related PRs
Suggested reviewers
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Code Review
이 PR은 Vite 개발 환경에서 발생하던 프록시 순환 참조 문제를 해결하고, API 호출 시 환경 변수를 일관되게 사용하도록 개선하는 중요한 변경을 포함하고 있습니다. VITE_PROXY_TARGET 환경 변수를 새로 도입하여 프록시 설정을 명확히 분리한 점과, 모든 API 요청에서 하드코딩된 /api 대신 VITE_API_BASE_URL을 사용하도록 통일한 점은 코드의 유지보수성과 설정 유연성을 크게 향상시킵니다. 전반적으로 훌륭한 개선입니다. 한 가지, API 응답 처리 시 타입 캐스팅이 일관되지 않은 부분이 있어 관련하여 리뷰 코멘트를 남겼습니다. 이 부분을 통일하면 코드의 타입 안정성이 더욱 높아질 것입니다.
| const url = `${import.meta.env.VITE_API_BASE_URL}/clubs?category=${filter}`; | ||
| const response = await fetch(url); | ||
|
|
||
| return await response.json(); |
There was a problem hiding this comment.
함수 반환 타입으로 Promise<ClubResponse>가 명시되어 있지만, response.json()은 Promise<any>를 반환하므로 타입 안정성이 떨어질 수 있습니다. 다른 API 파일(예: src/pages/user/ClubDetail/api/clubDetail.ts)에서는 as Promise<Type>과 같이 명시적 타입 캐스팅을 사용하고 있습니다. 코드베이스 전체의 일관성과 타입 안정성을 위해 아래와 같이 수정하는 것을 제안합니다.
이러한 변경을 타입 캐스팅이 누락된 다른 API 호출 함수(예: fetchComments in comments.ts, fetchDetailApplication in detailApplication.ts 등)에도 일관되게 적용하는 것을 고려해 보세요.
| return await response.json(); | |
| return response.json() as Promise<ClubResponse>; |
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/pages/admin/ApplicationDetail/api/comments.ts (1)
3-56: Add runtime validation for VITE_API_BASE_URL.All four functions construct URLs using
import.meta.env.VITE_API_BASE_URLwithout validating its presence. If this environment variable is undefined or empty, URLs will be malformed (e.g.,"undefined/applications/..."or"/applications/..."), causing fetch requests to fail with confusing errors.Consider adding validation at the module level:
import type { Comment } from '@/pages/admin/ApplicationDetail/types/comments'; + +const API_BASE_URL = import.meta.env.VITE_API_BASE_URL; +if (!API_BASE_URL) { + throw new Error('VITE_API_BASE_URL environment variable is not defined'); +} export const fetchComments = async (applicationId: number): Promise<Comment[]> => { - const url = `${import.meta.env.VITE_API_BASE_URL}/applications/${applicationId}/comments`; + const url = `${API_BASE_URL}/applications/${applicationId}/comments`; const response = await fetch(url);Apply the same pattern to all functions in this file.
♻️ Duplicate comments (1)
src/pages/admin/Dashboard/api/dashboard.ts (1)
4-5: LGTM!The URL construction follows the same pattern as other API modules in this PR.
Note: Same environment variable verification as mentioned in other files applies here.
🧹 Nitpick comments (1)
vite.config.ts (1)
22-26: Consider adding fallback for undefined environment variables.If
VITE_PROXY_TARGETis undefined, the proxy will silently fail withtarget: undefined. Consider adding a fallback or validation:server: { proxy: { '/api': { - target: env.VITE_PROXY_TARGET, + target: env.VITE_PROXY_TARGET || 'http://localhost:8080', changeOrigin: true, secure: false, }, }, },Alternatively, add explicit validation at the top of the config:
export default ({ mode }: ConfigEnv) => { const env = loadEnv(mode, process.cwd(), ''); if (mode === 'development' && !env.VITE_PROXY_TARGET) { throw new Error('VITE_PROXY_TARGET must be defined in .env.development'); } return defineConfig({ // ... }); };
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (9)
src/pages/admin/ApplicationDetail/api/comments.ts(4 hunks)src/pages/admin/ApplicationDetail/api/detailApplication.ts(2 hunks)src/pages/admin/ClubDetailEdit/api/clubDetailEdit.ts(1 hunks)src/pages/admin/Dashboard/api/applicant.ts(1 hunks)src/pages/admin/Dashboard/api/dashboard.ts(1 hunks)src/pages/user/Apply/api/apply.ts(2 hunks)src/pages/user/ClubDetail/api/clubDetail.ts(1 hunks)src/pages/user/Main/api/club.ts(1 hunks)vite.config.ts(1 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
src/pages/admin/ClubDetailEdit/api/clubDetailEdit.ts (1)
src/pages/admin/ClubDetailEdit/types/clubDetailEdit.ts (1)
ClubDetailEdit(3-3)
src/pages/user/ClubDetail/api/clubDetail.ts (1)
src/pages/user/ClubDetail/types/clubDetail.ts (1)
ClubDetail(3-20)
🔇 Additional comments (7)
src/pages/admin/Dashboard/api/applicant.ts (1)
4-4: Verify VITE_API_BASE_URL is configured correctly for the environment.The URL construction correctly uses the environment variable. Ensure that:
- In development:
VITE_API_BASE_URL='/api'(to use the Vite proxy)- In production:
VITE_API_BASE_URL='https://actual-backend-url'(to bypass proxy)If
VITE_API_BASE_URLis undefined, this will generate invalid URLs likeundefined/clubs/....src/pages/user/Main/api/club.ts (1)
9-10: LGTM!The URL construction follows the established pattern, and extracting the URL to an intermediate variable improves readability.
src/pages/user/ClubDetail/api/clubDetail.ts (1)
4-10: LGTM!Both changes improve the code:
- URL construction now uses the environment base URL (consistent with other files)
- Variable rename from
restoresponseimproves readabilitysrc/pages/user/Apply/api/apply.ts (1)
9-9: LGTM!Both API endpoints correctly use the environment base URL, maintaining consistency with the broader PR changes.
Also applies to: 23-23
src/pages/admin/ClubDetailEdit/api/clubDetailEdit.ts (1)
4-4: LGTM!Both fetch and update operations correctly use the environment base URL for consistency across all API calls.
Also applies to: 17-17
src/pages/admin/ApplicationDetail/api/detailApplication.ts (1)
7-7: LGTM!Both endpoints correctly use the environment base URL, completing the migration of all API calls in this PR to the environment-based configuration.
Also applies to: 18-18
src/pages/admin/ApplicationDetail/api/comments.ts (1)
4-4: Verify VITE_API_BASE_URL in environment configs
No.envfiles were found in the repo—ensureVITE_API_BASE_URLis defined in all your environment configuration files (e.g..env,.env.development,.env.production,.env.test) and that its value does not include a trailing slash.
| proxy: { | ||
| '/api': { | ||
| target: env.VITE_API_BASE_URL, | ||
| target: env.VITE_PROXY_TARGET, |
There was a problem hiding this comment.
🧩 Analysis chain
Verify environment variable configuration.
The proxy target change correctly addresses the circular reference issue. However, ensure that .env.development defines both VITE_PROXY_TARGET (pointing to the actual backend server) and VITE_API_BASE_URL (likely set to /api to trigger the proxy in development).
Run the following script to verify the environment configuration:
🏁 Script executed:
#!/bin/bash
# Description: Verify .env.development exists and contains required variables
if [ -f ".env.development" ]; then
echo "=== .env.development contents ==="
cat .env.development
echo ""
# Check for required variables
if grep -q "VITE_PROXY_TARGET" .env.development; then
echo "✓ VITE_PROXY_TARGET is defined"
else
echo "✗ VITE_PROXY_TARGET is NOT defined"
fi
if grep -q "VITE_API_BASE_URL" .env.development; then
echo "✓ VITE_API_BASE_URL is defined"
else
echo "✗ VITE_API_BASE_URL is NOT defined"
fi
else
echo "✗ .env.development file not found"
fiLength of output: 33
🏁 Script executed:
#!/bin/bash
# List all environment configuration files and check for required variables
echo "=== Env files found ==="
ls -1 .env* 2>/dev/null || echo "No .env files found"
for file in .env*; do
if [ -f "$file" ]; then
echo ""
echo "=== Checking $file ==="
grep -H "VITE_PROXY_TARGET" "$file" || echo "✗ VITE_PROXY_TARGET not found in $file"
grep -H "VITE_API_BASE_URL" "$file" || echo "✗ VITE_API_BASE_URL not found in $file"
fi
doneLength of output: 43
Enforce definition or fallback for VITE_PROXY_TARGET and VITE_API_BASE_URL
No .env files were found — both variables are undefined at runtime, so the dev proxy will fail. Either supply a .env.* with these keys or add a default/fallback in vite.config.ts.
🤖 Prompt for AI Agents
In vite.config.ts around line 23, VITE_PROXY_TARGET (and similarly
VITE_API_BASE_URL) may be undefined at runtime because no .env files were
loaded; update the config to provide safe fallbacks or fail fast: read the env
variables and assign sensible defaults (or throw a clear error) before using
them in the dev proxy and base URL, e.g. ensure target = env.VITE_PROXY_TARGET
?? 'http://localhost:3000' and base = env.VITE_API_BASE_URL ?? '/api' (or
validate and exit with a helpful message if you require explicit values).
…y-config-error#162 [FIX] 개발 환경 프록시 순환 참조 문제 해결 및 설정 개선
…y-config-error#162 [FIX] 개발 환경 프록시 순환 참조 문제 해결 및 설정 개선
#️⃣연관된 이슈
📝작업 내용
개발 환경에서 Vite proxy가 올바르게 작동하도록 환경 변수 구조를 개선했습니다.
문제 원인
npm run dev실행 시, Vite가 /api 코드를 포함한 .env.development 파일을 읽습니다.
동시에 Vite 프록시 설정의 target 또한 /api로 지정되어 있었기 때문에, 프론트엔드에서 /api/clubs/...로 요청을 보낼 경우
다음과 같은 문제가 발생
프록시가 자기 자신을 계속 호출하는 무한 루프가 발생
VITE_PROXY_TARGET 환경 변수 추가
vite.config.ts의 proxy target을VITE_PROXY_TARGET으로 변경상대경로 url에서 절대경로로 수정
💬리뷰 요구사항(선택)