[NextJs] nextJs에서 Proxy설정하기

Mincho·2023년 6월 23일
0

[NextJs]

목록 보기
9/12

🔴 컴포넌트

개발 과정에서 프론트와 백엔드의 api통신을 하다보면 cors오류는 생기기 마련이다. 그렇기에 이를 위해 proxy를 설정하여 우회하여 백엔드와 통신하고 있었다. React에서의 proxy설정
하지만 NextJs에서의 proxy설정 방법은 React와는 조금의 차이가 있다.



🟠 Next Js Rewrites

 NextJs공식 문서에서를 확인하면 rewrites기능은 프록시 기능을 하여 대상 경로를 마스킹하여 사용자가 사이트에서 자신의 위치를 변경하지 않은 것처럼 보이게 한다.

-source : 들어오는 요청 경로 패턴
-destination : 라우팅하려는 경로



🟡 활용

//next.config.js
const nextConfig = {
  async rewrites() {
    return [
      {
        source: "/api/v2/:path*/",
        destination: `통신하고자 하는 api url/:path*/`
      },
    ];
  },
  trailingSlash: true,
};

module.exports = withBundleAnalyzer(nextConfig);
//axiosSetting.ts
import axios from "axios";

import Cookies from "js-cookie";

export const instance = axios.create({
  baseURL: "/api/v2/",
  headers: {
    "X-CSRFToken": Cookies.get("csrftoken") || "",
  },
  withCredentials: true,
});

/**로그인 */
export const postLogin = (loginInform: any) =>
  instance.post(`/oauth/login/`, loginInform).then((res) => res.data);

  위와 같이 next.config.js에 api url을 입력하였고 axiosSetiing.ts파일의 instance에 baseURL의 source를 /api/v2/로 설정해두 었다. axios를 인스턴스화 해서 post 요청을 처리하였다.



🟢 주의해야 할 점(trailingSlash)

nextJS에서는 기본적으로 url을 후행슬래시가 없는 url로 리디렉션한다. 예를 들어 https://example.com/이라는 주소를 https://example.com로 리디렉션하는 것이다.
통신하려는 api uri가 후행 슬래쉬가 존재한다면 이는 nextJs에서의 처리 때문에 곤란할 수 있다.

const nextConfig = {
  async rewrites() {
    return [
      {
        source: "/api/v2/:path*/",
        destination: `${process.env.NEXT_PUBLIC_DEV_BASE_URL}/:path*/`
      },
    ];
  },
  trailingSlash: true,
};

 이를 위해 trailingSlash옵션을 true로 설정하면, 후행 슬래시가 있는 방식으로 동작하게 구성할 수 있다.



🔵 proxy를 사용한 결과(나의 적용기)

proxy로 우회하여 login요청을 보내 같은 로컬 도메인으로 session ID를 받아 올 수 있었다.

👍올바른 피드백은 언제든지 환영입니다~!

profile
사진찍는 개발자.

0개의 댓글