Next.js Discord

Discord Forum

NEXT_REDIRECT error

Answered
NanotechPikachu posted this in #help-forum
Open in Discord
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

Help?
Note: it's inside try block
@NanotechPikachu Note: it's inside try block
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
@gin u dont need cookies-next
I need it for cookies....
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
If you really want to use cookies-next then pass the cookies function to it

import { cookies } from 'next/headers';

setCookie('test1', 'value', { cookies });