Next.js에서 redirect를 설정하려면 다음과 같이 하면 된다.
next.config.js
const nextConfig = {
reactStrictMode: true,
async redirects() {
return [
{
source: "/a",
destination: "/b",
permanent: true,
},
];
},
};
option들을 하나씩 살펴보자
source
는 유저가 입력하게 되는 경로이고,
destination
은 유저가 입력한 경로를 검색했을 때 보내주고 싶은 경로를 입력하면 된다.
위의 코드에서 유저들은 /a 로 검색해도 /b로 url이 이동하게 되는 것이다.
그렇다면 마지막 permanent는 무엇일까?
permanent
는 true나 false를 리턴한다.
true의 경우 308 상태코드를 리턴받게 되는데, 이 때는 캐싱이 가능하다. 그러나 false의 경우에는 307 상태코드를 리턴받고 이 경우에는 임시이므로 캐싱되지 않는다.
307, 308 상태 코드와 비슷한 301(영구)과 302(임시)가 이미 있는데도 왜 Next는 307과 308을 사용할까?
공식문서에는 다음과 같이 나타나있다.
Why does Next.js use 307 and 308? Traditionally a 302 was used for a temporary redirect, and a 301 for a permanent redirect, but many browsers changed the request method of the redirect to GET, regardless of the original method. For example, if the browser made a request to POST /v1/users which returned status code 302 with location /v2/users, the subsequent request might be GET /v2/users instead of the expected POST /v2/users. Next.js uses the 307 temporary redirect, and 308 permanent redirect status codes to explicitly preserve the request method used.
301과 302는 redirect시킬때 get으로 method를 변경하고 body를 버리게 되므로 생각한 대로 동작이 안 될 수 있다. 그래서 Next는 307과 308을 도입하게 되었고, 이들은 기존 method도 유지하고 body도 버리지 않는다.