본문 바로가기

Study

[Next.js] redirects() 사용 시 페이지가 작동하지 않습니다. 이슈 해결하기

프로젝트를 진행하면서 /my-meeting/comments 라는 url에 접근하면, /my-meeting/comments/type=writable url로 접근하도록 하고 싶어, next.config.ts 파일에 다음과 같이 redirects() 옵션을 설정해주었다.

  async redirects() {
    return [
      {
        source: '/my-meeting/comments',
        destination: '/my-meeting/comments?type=writable',
        permanent: true,
      },
    ];
  },

이전에도 redirects()를 잘써왔었기 때문에 당연히 잘 작동할 줄 알았는데, 다음 화면을 마주했다.

왜 이런 문제가 발생한걸까? Next.js의 리디렉션 규칙은 요청 URL의 pathname만 검사한다.

  async redirects() {
    return [
      {
        source: '/my-meeting/',
        destination: '/my-meeting/my',
        permanent: true,
      },
    ];
  },

따라서 redirect()를 위와 같이 작성해왔다면, pathname이 /my-meeting 과 /my-meeting/my 로 다르기 때문에 리디렉션 후 재리디렉션 규칙에 걸리지 않아서 정상적으로 작동했을 것이다.

하지만

  async redirects() {
    return [
      {
        source: '/my-meeting/comments',
        destination: '/my-meeting/comments?type=writable',
        permanent: true,
      },
    ];
  },

위 처럼 작성할 경우 source와 destination의 pathname이 /my-meeting/comments 로 같기 때문에 리디렉션 후에도 동일한 규칙에 걸려 재리디렉션 되어 무한 리디렉션이 발생했던 것이다 🫠,,

 

그렇다면 어떻게 해결해야 될까?

 

같은 pathname에서 쿼리 파라미터가 없을 경우 리디렉션을 구현하는건 Next.js의 redirects()를 사용하기엔 한계가 있어 미들웨어를 사용하거나, 페이지 컴포넌트에서 router.push로 리다이렉트 시켜주어야 한다.

나는 페이지 컴포넌트를 서버 컴포넌트로 사용할거였기 때문에, 미들웨어를 사용해주었다.

  export async function middleware(request: NextRequest) {
  
  const { pathname, searchParams } = request.nextUrl;

  // /my-meeting/comments 경로에서 type 쿼리 파라미터가 없으면 writable로 세팅
  if (pathname === '/my-meeting/comments' && !searchParams.has('type')) {
    searchParams.set('type', 'writable');
    return NextResponse.redirect(request.nextUrl);
  }
  
  }

이제 /my-meeting/comments 라는 url에 접근하면, /my-meeting/comments/type=writable url로 접근이 잘된다!