개발 과정에서 프론트와 백엔드의 api통신을 하다보면
cors오류
는 생기기 마련이다. 그렇기에 이를 위해proxy
를 설정하여 우회하여 백엔드와 통신하고 있었다. React에서의 proxy설정
하지만 NextJs에서의 proxy설정 방법은 React와는 조금의 차이가 있다.
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 요청을 처리하였다.
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로 우회하여 login요청을 보내 같은 로컬 도메인으로 session ID를 받아 올 수 있었다.