Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions lib/axios.ts
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

File Walkthrough

Enhancement
axios.ts (+11/-0)
Axios 클라이언트 인스턴스 설정                                                                           

lib/axios.ts

  • Axios 인스턴스 생성 및 공통 설정 정의
  • baseURL, Content-Type 헤더, withCredentials 설정
  • 클라이언트 환경용 api 인스턴스 export
server-api.ts (+46/-0)
서버 환경 API 클라이언트 구현                                                                             

lib/server-api.ts

  • 서버 환경용 API 클라이언트 구현
  • next/headers의 cookies() 활용한 자동 쿠키 주입
  • GET, POST, PUT, DELETE, PATCH 메서드 제공
  • 제네릭 타입 지원으로 응답 타입 안정성 확보
Dependencies
package.json (+3/-0)
React Query 및 Axios 의존성 추가                                                             

package.json

  • @tanstack/react-query@^5.90.20 추가
  • @tanstack/react-query-devtools@^5.91.2 추가
  • axios@^1.13.3 추가
pnpm-lock.yaml (+113/-0)
패키지 잠금 파일 업데이트                                                                                     

pnpm-lock.yaml

  • React Query 및 관련 패키지 잠금 파일 업데이트
  • Axios 및 의존성(follow-redirects, form-data) 추가
  • mime-types, proxy-from-env 등 보조 패키지 포함

Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import axios from "axios";

// 1. 공통 설정 (URL, 헤더 등)
const axiosConfig = {
baseURL: process.env.NEXT_PUBLIC_API_URL,
headers: { "Content-Type": "application/json" },
withCredentials: true,
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

클라이언트 환경에서 withCredentials: true 설정은 브라우저가 자동으로 쿠키를 포함하도록 하여 유용합니다. 하지만 이 axiosConfig를 사용하여 생성된 api 인스턴스가 lib/server-api.ts에서 서버 환경 요청에도 재사용되고 있습니다. 서버 환경에서는 withCredentials 설정이 무의미하며, next/headerscookies()를 통해 쿠키를 수동으로 주입하는 방식이 올바릅니다. 코드의 의도를 더욱 명확히 하고 잠재적인 혼란을 방지하기 위해, 서버 전용 axios 인스턴스를 따로 생성하여 withCredentials: false로 설정하거나, axiosConfig에서 withCredentials를 제거하고 클라이언트용 api 인스턴스 생성 시에만 명시적으로 withCredentials: true를 적용하는 것을 고려해볼 수 있습니다. 현재 구현 방식이 동작에는 문제가 없을 수 있으나, 명확성을 위해 제안합니다.

};

// 2. 클라이언트용(CSR) 인스턴스 생성 및 export
export const api = axios.create(axiosConfig);
46 changes: 46 additions & 0 deletions lib/server-api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { cookies } from "next/headers";
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

cookies() 함수는 Next.js의 Server Components 또는 Server Actions에서만 호출되어야 합니다. 현재 lib/server-api.ts 파일은 서버 환경에서만 사용될 것으로 예상되지만, 실수로 클라이언트 컴포넌트에서 이 파일을 import 하여 request 함수를 호출할 경우 런타임 에러가 발생할 수 있습니다. 이를 방지하고 파일의 의도를 명확히 하기 위해 파일 상단에 'use server' 지시어를 추가하여 해당 파일이 Server Action으로 동작하도록 명시하는 것을 권장합니다. 이는 빌드 시점에 잠재적인 문제를 감지하는 데 도움이 됩니다.

Repository Style Guide 2.2

Suggested change
import { cookies } from "next/headers";
'use server';
import { cookies } from "next/headers";

import { api } from "./axios";
import type { AxiosRequestConfig, AxiosResponse } from "axios";

// 서버 환경에서 사용할 API 클라이언트입니다.
// next/headers의 cookies()를 사용하여 요청에 자동으로 쿠키를 포함시킵니다.
async function request<T>(
config: AxiosRequestConfig,
): Promise<AxiosResponse<T>> {
const cookieStore = await cookies();
const cookieHeader = cookieStore.toString();
Comment on lines +10 to +11
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

critical

안녕하세요. cookies()에서 반환된 cookieStore 객체에 toString() 메서드를 사용하는 것은 쿠키 문자열을 직렬화하는 안정적인 방법이 아닙니다. ReadonlyRequestCookies 타입에는 toString()이 공식적으로 정의되어 있지 않아 예상치 못한 동작이나 오류를 발생시킬 수 있습니다.

cookieStore.getAll()을 사용하여 모든 쿠키를 배열로 가져온 후, 이를 key=value 형태의 문자열로 조합하여 Cookie 헤더를 생성하는 것이 올바른 방법입니다. 아래 제안 코드를 참고하여 수정하시는 것을 권장합니다.

  const cookieStore = await cookies();
  const cookieHeader = cookieStore
    .getAll()
    .map((cookie) => `${cookie.name}=${cookie.value}`)
    .join("; ");


return api({
...config,
headers: {
...config.headers,
...(cookieHeader && { Cookie: cookieHeader }),
},
});
}
Comment on lines +1 to +20
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

현재 serverApi 함수는 GET 요청에만 사용 가능하도록 하드코딩되어 있습니다. 이는 향후 POST, PUT, DELETE 등 다른 HTTP 메소드를 사용해야 할 때 코드 중복을 유발하고 확장성을 저해할 수 있습니다. 보다 일반적이고 재사용 가능한 구조로 리팩토링하는 것을 강력히 권장합니다. 예를 들어, serverApi를 각 HTTP 메소드를 지원하는 함수를 가진 객체로 만들면 API의 일관성을 유지하고, 새로운 HTTP 메소드가 필요할 때 쉽게 확장할 수 있습니다.

import { cookies } from "next/headers";
import { api } from "./axios";
import type { AxiosRequestConfig, AxiosResponse } from "axios";

// 서버 환경에서 사용할 API 클라이언트입니다.
// next/headers의 cookies()를 사용하여 요청에 자동으로 쿠키를 포함시킵니다.
async function request<T>(config: AxiosRequestConfig): Promise<AxiosResponse<T>> {
  const cookieStore = await cookies();
  const cookieHeader = cookieStore.toString();

  return api({
    ...config,
    headers: {
      ...config.headers,
      ...(cookieHeader && { Cookie: cookieHeader }),
    },
  });
}

export const serverApi = {
  get: <T = any>(url: string, config?: AxiosRequestConfig) =>
    request<T>({ ...config, method: "GET", url }),

  post: <T = any>(url: string, data?: any, config?: AxiosRequestConfig) =>
    request<T>({ ...config, method: "POST", url, data }),

  put: <T = any>(url: string, data?: any, config?: AxiosRequestConfig) =>
    request<T>({ ...config, method: "PUT", url, data }),

  delete: <T = any>(url: string, config?: AxiosRequestConfig) =>
    request<T>({ ...config, method: "DELETE", url }),

  patch: <T = any>(url: string, data?: any, config?: AxiosRequestConfig) =>
    request<T>({ ...config, method: "PATCH", url, data }),
};
References
  1. 함수 이름이 의미론적이어야 하며(52), 코드 중복을 피하기 위해 재사용 가능한 유틸리티로 추출해야 합니다(54). 현재 serverApi는 GET만 지원하여 이름이 오해의 소지가 있고, 다른 메소드 추가 시 코드 중복이 발생할 수 있습니다. (link)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

반영함


export const serverApi = {
get: <T = unknown>(url: string, config?: AxiosRequestConfig) =>
request<T>({ ...config, method: "GET", url }),

post: <T = unknown>(
url: string,
data?: unknown,
config?: AxiosRequestConfig,
) => request<T>({ ...config, method: "POST", url, data }),
Comment on lines +26 to +30
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

타입 안정성 및 개발자 경험 향상을 위해 post 메서드의 data 파라미터 타입을 unknown 대신 제네릭 D로 지정하는 것을 제안합니다. 이렇게 하면 serverApi.post를 호출하는 쪽에서 요청 본문의 타입을 명시할 수 있어 타입 추론이 더 원활해지고 코드의 안정성이 높아집니다. 이는 레포지토리 스타일 가이드에서 강조하는 타입 안정성 원칙과도 부합합니다. put, patch 메서드에도 동일하게 적용할 수 있습니다.

  post: <T = unknown, D = unknown>(
    url: string,
    data?: D,
    config?: AxiosRequestConfig,
  ) => request<T>({ ...config, method: "POST", url, data }),
References
  1. Server Actions 함수는 인자와 반환값에 대한 명확한 타입을 가져야 합니다. 이 원칙은 서버 환경 API 클라이언트에도 동일하게 적용하여 타입 안정성을 높이는 것이 좋습니다. (link)
  2. any 타입 사용을 금지하고, unknown이나 never를 활용하여 타입을 좁히도록 권장합니다. 제네릭을 활용하면 unknown보다 더 구체적인 타입 추론이 가능해져 코드의 안정성을 높일 수 있습니다. (link)


put: <T = unknown>(
url: string,
data?: unknown,
config?: AxiosRequestConfig,
) => request<T>({ ...config, method: "PUT", url, data }),
Comment on lines +32 to +36
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

타입 안정성 및 개발자 경험 향상을 위해 put 메서드의 data 파라미터 타입을 unknown 대신 제네릭 D로 지정하는 것을 제안합니다. 이렇게 하면 serverApi.put을 호출하는 쪽에서 요청 본문의 타입을 명시할 수 있어 타입 추론이 더 원활해지고 코드의 안정성이 높아집니다. 이는 레포지토리 스타일 가이드에서 강조하는 타입 안정성 원칙과도 부합합니다.

  put: <T = unknown, D = unknown>(
    url: string,
    data?: D,
    config?: AxiosRequestConfig,
  ) => request<T>({ ...config, method: "PUT", url, data }),
References
  1. Server Actions 함수는 인자와 반환값에 대한 명확한 타입을 가져야 합니다. 이 원칙은 서버 환경 API 클라이언트에도 동일하게 적용하여 타입 안정성을 높이는 것이 좋습니다. (link)
  2. any 타입 사용을 금지하고, unknown이나 never를 활용하여 타입을 좁히도록 권장합니다. 제네릭을 활용하면 unknown보다 더 구체적인 타입 추론이 가능해져 코드의 안정성을 높일 수 있습니다. (link)


delete: <T = unknown>(url: string, config?: AxiosRequestConfig) =>
request<T>({ ...config, method: "DELETE", url }),

patch: <T = unknown>(
url: string,
data?: unknown,
config?: AxiosRequestConfig,
) => request<T>({ ...config, method: "PATCH", url, data }),
Comment on lines +41 to +45
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

타입 안정성 및 개발자 경험 향상을 위해 patch 메서드의 data 파라미터 타입을 unknown 대신 제네릭 D로 지정하는 것을 제안합니다. 이렇게 하면 serverApi.patch를 호출하는 쪽에서 요청 본문의 타입을 명시할 수 있어 타입 추론이 더 원활해지고 코드의 안정성이 높아집니다. 이는 레포지토리 스타일 가이드에서 강조하는 타입 안정성 원칙과도 부합합니다.

  patch: <T = unknown, D = unknown>(
    url: string,
    data?: D,
    config?: AxiosRequestConfig,
  ) => request<T>({ ...config, method: "PATCH", url, data }),
References
  1. Server Actions 함수는 인자와 반환값에 대한 명확한 타입을 가져야 합니다. 이 원칙은 서버 환경 API 클라이언트에도 동일하게 적용하여 타입 안정성을 높이는 것이 좋습니다. (link)
  2. any 타입 사용을 금지하고, unknown이나 never를 활용하여 타입을 좁히도록 권장합니다. 제네릭을 활용하면 unknown보다 더 구체적인 타입 추론이 가능해져 코드의 안정성을 높일 수 있습니다. (link)

};
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@
"prepare": "husky"
},
"dependencies": {
"@tanstack/react-query": "^5.90.20",
"@tanstack/react-query-devtools": "^5.91.2",
"axios": "^1.13.3",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"lucide-react": "^0.562.0",
Expand Down
113 changes: 113 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.