NextJS | Redirect

이동주·2022년 6월 22일

NextJS

목록 보기
2/2
post-thumbnail

Next.js에서 커스텀 설정을 하려면?

프로젝트 디렉터리의 루트에 next.config.js || next.config.mjs 파일을 만든다.
next.config.js는 JSON 파일이 아닌 일반 Node.js 모듈.
Next.js 서버 및 빌드 단계에서 사용되며 브라우저 빌드에는 포함되지 않음.

Redirects?

Redirect을 사용하면 들어오는 request 경로를 다른 destination 경로로 Redirect 할 수 있다.
redirects은 source, destinationpermanent 속성이 있는 객체를 포함하는 배열을 반환하는 비동기 함수.

Redirect을 사용법

=> next.config.js에서 redirects 함수 사용

  • source
    : 들어오는 request 경로 패턴 (request 경로)
  • destination
    : 라우팅하려는 경로 (redirect할 경로)
  • permanent
    • true인 경우 클라이언트와 search 엔진에 redirect를 영구적으로 cache하도록 지시하는 308 status code를 사용
    • false인 경우 일시적이고 cache되지 않은 307 status code를 사용
    • 브라우저나 검색엔진이 정보를 기억하는데에 결정 됨

기본 redirect 코드

const nextConfig = {
  reactStrictMode: true,
  async redirects() {
    return [
      {
        source: "/contact",
        destination: "/form",
        permanent: false,
      },
    ];
  },
};

module.exports = nextConfig;

추가로 contact 부분에 :path 입력하면 사용자가 적는 값(아이디)을 받을 수 있고, :path* 입력하면 사용자가 적는 모든 값을 받는다.!

source: "/contact:path",
destination: "/form:path",
source: "/contact:path*",
destination: "/form:path*",
profile
안녕하세요 이동주입니다

0개의 댓글