Here is the code snippet from my /app/api/auth/route.ts
file:
import { redirect } from 'next/navigation';
export async function GET(req: Request) {
try {
redirect('/dashboard');
} catch (error) {
console.log(error);
redirect('/');
}
}
After some testing, I discovered that using a try-catch block with redirection can result in the following error:
Error: NEXT_REDIRECT
at getRedirectError (webpack-internal:///(sc_server)/./node_modules/next/dist/client/components/redirect.js:40:19)
at redirect (webpack-internal:///(sc_server)/./node_modules/next/dist/client/components/redirect.js:46:11)
at GET (webpack-internal:///(sc_server)/./app/api/auth/route.ts:23:66)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async eval (webpack-internal:///(sc_server)/./node_modules/next/dist/server/future/route-modules/app-route/module.js:244:37) {
digest: 'NEXT_REDIRECT;replace;/dashboard'
}
I found that removing the try-catch block resolved the issue:
export async function GET(req: Request) {
redirect('/dashboard')
}
This change worked as expected. Although I originally included the try-catch for error handling in this authorization route, it seems like its presence causes this specific problem. If there's a different approach to error handling in /api
routes in Next 13, I would appreciate any suggestions.