Next.js Discord

Discord Forum

NEXT_REDIRECT error

Answered
NanotechPikachu posted this in #help-forum
Open in Discord
Avatar
NanotechPikachuOP
I am trying to use redirect() in route.js file of mine but, it's always giving me the NEXT_REDIRECT error.

My main code somewhat looks like this
import { setCookie } from 'cookies-next';
import { NextResponse } from 'next/server';
import { redirect } from 'next/navigation';

const res = new NextResponse(//json data here)
setCookie(//cookie set)
redirect('/guilds');
return res

This is a GET in route.js

Plz help!!!
Thnx
Answered by joulev
redirect throws a special error so should not be put inside try/catch.

if you must put it inside try/catch, you have to rethrow it:
import { isRedirectError } from "next/dist/client/components/redirect";

try {
  ...
} catch (error) {
  if (isRedirectError(error)) throw error;
  console.log(error);
}
View full answer

14 Replies

Avatar
NanotechPikachuOP
Help?
Avatar
NanotechPikachuOP
Note: it's inside try block
Avatar
gin
u dont need cookies-next
also u dont need to invoke a new NextResponse instance
and you should use redirect with a return statement
in route handlers or any other server component
Avatar
joulev
redirect throws a special error so should not be put inside try/catch.

if you must put it inside try/catch, you have to rethrow it:
import { isRedirectError } from "next/dist/client/components/redirect";

try {
  ...
} catch (error) {
  if (isRedirectError(error)) throw error;
  console.log(error);
}
Answer
Avatar
NanotechPikachuOP
I need it for cookies....
Ok sir. I tried it now. Works

finally also works
Avatar
NanotechPikachuOP
Just a question, can we make a html content to be displayed in route.js like a button?
Cuz when i redirect, the cookie isn't being set.

Only found that error now cuz my cookie expired and when I tried login and redirect happened, the cookie isn't being set
Avatar
joulev
Just use cookies().set(), the cookies will be set
If you really want to use cookies-next then pass the cookies function to it

import { cookies } from 'next/headers';

setCookie('test1', 'value', { cookies });
Avatar
NanotechPikachuOP
Thnx sir. It worked!