😵‍💫

【Next.js 15/AppRouter】サーバーサイドでリダイレクトするときの注意

2025/03/10に公開

【Next.js 15/AppRouter】サーバーサイドでリダイレクトするときの注意

困りごと

Next13からNext15のAppRouterに移行していて、これまで問題なくリダイレクトしていた箇所でエラーが発生するように

結論

try-catchの中だとリダイレクトできない
https://github.com/vercel/next.js/issues/74258

原因

NextJS throws a 303 error when you call redirect.

Issueにあるように、Next.jsでリダイレクトをしようとすると、303エラーを発生させ、それがtry-catchに捕まったようです。

The issue arises from the try block on the client catching the 303 error from the redirect.
But this wasn't a behaviour in Next14. In Next14, the server action will return undefined when you redirect, which can cause issues, because the return type for the server action will not reflect that.

Next14まではこのエラーではなく、undefinedを返していたので、try-catchでも問題なかったと。
Next15にしてからredirect()の挙動が変わり、errorを投げるようになったので発生したと。

公式ドキュメント

https://nextjs.org/docs/app/api-reference/functions/redirect

Good to knowにちょこっと書いてありました。

In Server Actions and Route Handlers, redirect should be called after the try/catch block.

補足

数週間前に、この記事見てたのに速攻で気づけなかったの悔しい、、、

[Next.js]Next.jsではtry-catchしない方が無難
https://zenn.dev/urotea/articles/6320efaf9bc78e

Discussion