英文:
Next 13.4 Error: NEXT_REDIRECT in API routes
问题
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('/');
  }
}
I realized that when I do redirect in a try catch, I get the 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'
}
When I get rid of the try-catch, everything works fine:
export async function GET(req: Request) {
  redirect('/dashboard')
}
This works as expected. I need try and catch because this is an auth route and I need some error handling because the request could fail. I have left out the auth functionalities because I realized that this happens just on a simple try and catch.
Or if Next 13 has another way of error handling in /api routes, please let me know.
英文:
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('/');
  }
}
I realized that when I do redirect in a try catch, I get the 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'
}
When I get get rid of the try catch everything works fine:
export async function GET(req: Request) {
  redirect('/dashboard')
}
This works as expected. I need try and catch because this is an auth route and I need some error handling because the request could fail, I have left out the auth functionalities becuase I realized that this happens just on a simple try and catch.
Or if Next 13 has another way of error handling in /api routes please let me know.
答案1
得分: 16
"At the moment, the workaround I found is to not use:
import { redirect } from 'next/navigation';
But to use instead:
import { useRouter } from 'next/navigation'
const router = useRouter()
router.push('/')"
英文:
At the moment, the workaround I found is to not use:
import { redirect } from 'next/navigation';
But to use instead:
import { useRouter } from 'next/navigation'
const router = useRouter()
router.push("/")
答案2
得分: 3
这是因为在内部,redirect()引发了一个错误。
请参阅https://github.com/vercel/next.js/blob/canary/packages/next/src/client/components/redirect.ts#L16-L41C2
英文:
This is because internally, redirect() is throwing an Error.
See https://github.com/vercel/next.js/blob/canary/packages/next/src/client/components/redirect.ts#L16-L41C2
答案3
得分: 1
使用以下代码在 Next.js 13+ 应用的服务器端重定向到新的 URL:
return NextResponse.redirect(new URL('/home', request.url))
英文:
use
return NextResponse.redirect(new URL('/home', request.url))
in next 13+ app dir server side
答案4
得分: 1
以下是您提供的代码的翻译部分:
"use server"
import LoginSchema from "@/Schemas/LoginSchema";
import PocketBase from 'pocketbase';
import { redirect } from 'next/navigation';
const analyze = async(data) =>{
const pb = new PocketBase('http://127.0.0.1:8090');
try{
const authData = await pb.collection('UserTable').authWithPassword(await data.Email, await data.Password);
if (authData){
return authData
}
}
catch(error){
error
}
}
export async function LoginAction(data) {
const result = await LoginSchema.isValid(await data)
if (result === true) {
const result = await analyze(data)
if(result){
return redirect("/")
}
else{
return "failed"
}
}
else {
    return "failed"
}
}
英文:
Its easy to fix it. currently there is a bug in try catch block with next redirect. but you dont need to chancge anything. you just need to transfer try, cath block in different function thats it. i give you example of my code
"use server"
import LoginSchema from "@/Schemas/LoginSchema";
import PocketBase from 'pocketbase';
import { redirect } from 'next/navigation'
const analyze = async(data) =>{
    const pb = new PocketBase('http://127.0.0.1:8090');
    try{
        const authData = await pb.collection('UserTable').authWithPassword(await data.Email, await data.Password);
        if (authData){
            return authData
        }
    }
    catch(error){
        error
    }
}
export async function LoginAction(data) {
    const result = await LoginSchema.isValid(await data)
    if (result === true) {
        const result = await analyze(data)
        if(result){
            return redirect("/")
        }
        else{
            return "failed"
        }
        
    }
    else {
        return "failed"
    }
}
答案5
得分: 0
The error that I got was Uncaught (in promise) Error: NEXT_REDIRECT
And I'm not sure if this is a bug... Because the method needs context info that is available inside "react render time!".
So this will work if you create a reference to use it later.
import { useRouter } from 'next/navigation'
function reactFunctionComponent() {
  const router = useRouter()
  runWithPromise().then( () => router.push("/") )
  ...
}
英文:
The error that I got was Uncaught (in promise) Error: NEXT_REDIRECT
And I'm not sure if this is a bug... Because the method needs context info that is available inside "react render time!".
So this will work if you create a reference to use it later.
import { useRouter } from 'next/navigation'
function reactFunctionComponent() {
  const router = useRouter()
  runWithPromise().then( () => router.push("/") )
  ...
}
答案6
得分: 0
这发生在我使用 try...catch 语句时。以一种不需要 try...catch 语句的方式重写了我的代码,现在它正常运行。这不一定只发生在 API 路由文件中,也可能发生在 React 组件中,在其中在 try catch 内部调用了重定向。
英文:
This happened to me when I used a try...catch statement. Rewrote my code in a way that didn't need a try...catch statement and it now works fine. This doesn't necessarily happen to API route files only, could happen in a react component where redirect is called inside a try catch.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论