본문 바로가기

NEXT.js

[Next.js] redirect 함수, notFound 함수는 try/catch 밖에서 사용해야 합니다

 

1. Next.js의 redirect 함수는 특별한 타입의 에러(NEXT_REDIRECT)를 throw하는 방식으로 작동합니다.

 

2. try/catch 블록 안에서 redirect를 사용하면 redirect가 던진 에러가 catch 블록에서 잡혀버리고

redirect 는 동작하지 않게 됩니다.

 

3. 클라이언트 컴포넌트의 경우,  useRouter를 사용하는 것이 더 적절할 수 있음

 

4. 추가로 notFound() 함수도 아래와 마찬가지 패턴으로 처리해야 합니다.

 

 

import { redirect } from 'next/navigation';


// ... 생략 ...
  let isRedirect = false;

  try {
// ... 생략 ...

    isRedirect = true;
  } catch (err) {
    console.error(err);
  }
  
  if (isRedirect) {
    redirect('/home');
  }
// ... existing code ...

 

위 내용은 아래의 링크에서도 확인 가능 합니다.

 

https://github.com/vercel/next.js/issues/49298

 

Error: NEXT_REDIRECT while using server actions · Issue #49298 · vercel/next.js

Verify canary release I verified that the issue exists in the latest Next.js canary release Provide environment information Operating System: Platform: darwin Arch: arm64 Version: Darwin Kernel Ver...

github.com

 

https://nextjs-ko.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations#redirecting

 

Server Actions and Mutations – Nextjs 한글 문서

Learn how to handle form submissions and data mutations with Next.js.

nextjs-ko.org