Next.js Discord

Discord Forum

Redirect in api route handler does not work!

Unanswered
Dwarf Crocodile posted this in #help-forum
Open in Discord
Avatar
Dwarf CrocodileOP
Using app router

and app/api/auth/route.ts

I have a function

 export async function POST(request: NextRequest) {
  redirect("/persons");


But it never redirect what I mean that browser URL path never changes.

I'm wondering if I'm missing anything else here?
Image

16 Replies

Avatar
what if you do return NextResponse.redirect(...)?
i feel like redirect() doesn't work sometimes, behaviour like you described has also been reported elsewhere in this server, it's a bug
Avatar
Dwarf CrocodileOP
So what can be an alternative?

Maybe using redirect from the client side??
Avatar
have you tried this? this is the alternative i suggest
Avatar
Dwarf CrocodileOP
It changes nothing!
Even docs also mention that return is not required when using redirect 🤷‍♂️
Avatar
yeah redirect and NextResponse.redirect are different functions and have different usage but should do the same thing
wait
how do you fetch the api route?
Avatar
fetch("/api/auth")?
if so, redirecting inside the api route itself will do nothing because it will just become fetch("/persons")
you have to use client-side useRouter to reach a new route
or use server actions instead where redirect works for your use case
Avatar
Dwarf CrocodileOP
So actually how can I write the redirects app level

Like if user is logged in already and trying to access auth routes it should get redirected to home.
And when not authenticated & accessing protected routes it should get redirected to auth route/page.

I'm looking for a generic approach ( app level config thingy ) rather having similar code pieces/logic everywhere.

If you have a code example maybe a repo or similar that will be super cool.
Avatar
so the bad news is, there is no single best way to do it. different libraries have different approaches. different people prefer different things. and if you bring your own auth, depending on how you implement it you might need different ways to do it.

but here are some common methods:
* redirect in middleware
* redirect via client-side rendering
* whenever you render protected data in a server component, you check authentication and if auth doesn't pass, you redirect