Skip to content

[FIX] 개발 환경 프록시 순환 참조 문제 해결 및 설정 개선#163

Merged
aaaaaattt merged 2 commits intodevelopfrom
fix/dev-proxy-config-error#162
Oct 12, 2025
Merged

[FIX] 개발 환경 프록시 순환 참조 문제 해결 및 설정 개선#163
aaaaaattt merged 2 commits intodevelopfrom
fix/dev-proxy-config-error#162

Conversation

@kanghaeun
Copy link
Contributor

@kanghaeun kanghaeun commented Oct 12, 2025

#️⃣연관된 이슈

close #162

📝작업 내용

개발 환경에서 Vite proxy가 올바르게 작동하도록 환경 변수 구조를 개선했습니다.

문제 원인

npm run dev실행 시, Vite가 /api 코드를 포함한 .env.development 파일을 읽습니다.
동시에 Vite 프록시 설정의 target 또한 /api로 지정되어 있었기 때문에, 프론트엔드에서 /api/clubs/...로 요청을 보낼 경우
다음과 같은 문제가 발생

  1. 브라우저가 /api/clubs/...로 요청을 전송
  2. Vite 프록시가 이 요청을 다시 target: '/api'로 전달하려 시도
  3. 결국 http://localhost:5173/api/...로 다시 요청이 돌아오며

프록시가 자기 자신을 계속 호출하는 무한 루프가 발생


  • VITE_PROXY_TARGET 환경 변수 추가

    • .env.development 파일에 프록시 목적지(실제 백엔드 서버 주소)를 명시하기 위한 VITE_PROXY_TARGET 변수를 추가
    • vite.config.ts의 proxy target을 VITE_PROXY_TARGET으로 변경
  • 상대경로 url에서 절대경로로 수정

// 수정 전
const url = /api/clubs/${clubId};
// 수정 후
  const url = ${import.meta.env.VITE_API_BASE_URL}/clubs/${clubId}/dashboard/applicants;

💬리뷰 요구사항(선택)

빠진 api 가 있다면 알려주세요!

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @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

  • 개발 환경 프록시 설정 개선: 개발 환경에서 Vite 프록시가 올바르게 작동하도록 환경 변수 구조를 개선했습니다.
  • VITE_PROXY_TARGET 환경 변수 추가: .env 파일에 프록시 목적지(실제 백엔드 서버 주소)를 명시하기 위한 VITE_PROXY_TARGET 변수를 추가하여 프록시 설정을 분리했습니다.
  • API 호출 경로 수정: 기존에 하드코딩된 /api 경로를 import.meta.env.VITE_API_BASE_URL을 사용하도록 변경하여 API 호출의 유연성을 높였습니다.
Using Gemini Code Assist

The 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 /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

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 .gemini/ folder in the base of the repository. Detailed instructions can be found here.

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

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@coderabbitai
Copy link

coderabbitai bot commented Oct 12, 2025

Note

Other AI code review bot(s) detected

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

Walkthrough

Updated 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

Cohort / File(s) Summary
Admin APIs: base URL migration
src/pages/admin/ApplicationDetail/api/comments.ts, src/pages/admin/ApplicationDetail/api/detailApplication.ts, src/pages/admin/ClubDetailEdit/api/clubDetailEdit.ts, src/pages/admin/Dashboard/api/applicant.ts, src/pages/admin/Dashboard/api/dashboard.ts
Replace relative API paths with absolute URLs using import.meta.env.VITE_API_BASE_URL; preserve methods, behavior, and error handling.
User APIs: base URL migration and small refactor
src/pages/user/Apply/api/apply.ts, src/pages/user/ClubDetail/api/clubDetail.ts, src/pages/user/Main/api/club.ts
Switch to environment-based base URL. In clubDetail.ts, rename local res to response; in club.ts, introduce intermediate url variable before fetch.
Build config: proxy target env var
vite.config.ts
Change dev proxy target from VITE_API_BASE_URL to VITE_PROXY_TARGET; other proxy options unchanged.

Sequence Diagram(s)

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related issues

Possibly related PRs

Suggested reviewers

  • ganimjeong
  • aaaaaattt

Poem

Hop hop! I tweak the paths I tread,
From /api lanes to ENV instead.
The proxy’s sign points new and bright,
So fetches find their way by night.
Carrots cached, requests in queue—
Base URLs guide me true. 🥕✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Title Check ✅ Passed The title clearly identifies the primary fix—resolving the development proxy circular reference—and also indicates general configuration improvements, which align with updating vite.config.ts and environment variables as described in the PR. It is concise, specific, and directly reflects the main objectives of the changeset.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
✨ 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 fix/dev-proxy-config-error#162

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.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

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();
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

함수 반환 타입으로 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 등)에도 일관되게 적용하는 것을 고려해 보세요.

Suggested change
return await response.json();
return response.json() as Promise<ClubResponse>;

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

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_URL without 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_TARGET is undefined, the proxy will silently fail with target: 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

📥 Commits

Reviewing files that changed from the base of the PR and between 69e7f35 and 1891f7d.

📒 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_URL is undefined, this will generate invalid URLs like undefined/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 res to response improves readability
src/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 .env files were found in the repo—ensure VITE_API_BASE_URL is 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,
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

🧩 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"
fi

Length 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
done

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

@kanghaeun kanghaeun self-assigned this Oct 12, 2025
@kanghaeun kanghaeun added the 🐛 bug 버그 이슈 label Oct 12, 2025
@aaaaaattt aaaaaattt merged commit ce21771 into develop Oct 12, 2025
11 checks passed
@aaaaaattt aaaaaattt deleted the fix/dev-proxy-config-error#162 branch October 12, 2025 16:53
ganimjeong pushed a commit that referenced this pull request Oct 27, 2025
…y-config-error#162

[FIX] 개발 환경 프록시 순환 참조 문제 해결 및 설정 개선
ganimjeong pushed a commit that referenced this pull request Oct 27, 2025
…y-config-error#162

[FIX] 개발 환경 프록시 순환 참조 문제 해결 및 설정 개선
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐛 bug 버그 이슈

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[FIX] 개발 환경 프록시 설정 오류로 인한 API 요청 실패 문제

3 participants