Next.js Discord

Discord Forum

Can't redirect client from 'app/api/endpoint'

Answered
Norwegian Buhund posted this in #help-forum
Open in Discord
Norwegian BuhundOP
Docs say use redirect() from next/navigate but it doesn't do anything
Answered by James4u
because you just hitted api and inside the api, it actually redirects
View full answer

38 Replies

How did you use that function?
Norwegian BuhundOP
i tried relative and absolute URLs
@Norwegian Buhund i tried relative and absolute URLs
Sun bear
Please show me your use example.
you need to explain further details to get good result.
In which file did you use, and what is error report?
Norwegian BuhundOP
kind of hard since this is a sensitive application
Norwegian BuhundOP
let's say i have:
- app/login/page.tsx - returns LoginClientWrapper, which has a useEffect that fetches '/api/login/qr' in a useEffect on mount
- app/api/login/qr/route.tsx - fetches google OAuth, then fetches a separate backend (/auth/google-signin), stores some cookies then returns NextResponse.json
- i need app/api/login/qr/route.tsx to redirect successful /auth/google-signin. I can confirm that all that data is getting received by the server. but i just can't get the client to redirect to any URL
redirect() inside try cath won't work @Norwegian Buhund
@James4u redirect() inside try cath won't work <@221775759218311171>
Norwegian BuhundOP
I'm not using try catch. Does it not work in async functions as well?
Norwegian BuhundOP
then not sure what the problem is
oh, I see
Norwegian BuhundOP
i'm seeing a server log for POST /api/login/qr 307 in 577ms but it's not navigating the client
so you make a fetch to /api/login/qr in useEffect() right?
and then inside that api, you did redirect() right?
Norwegian BuhundOP
yes
it doesn't do anything - because
@James4u and then inside that api, you did `redirect()` right?
Norwegian BuhundOP
don't think so
redirect is in api/login/qr/route.tsx
yeah, it's the api you are making a fetch request to, right?
Norwegian BuhundOP
yes
yeah, nothing happens then
Norwegian BuhundOP
oh im dumb
because you just hitted api and inside the api, it actually redirects
Answer
but as you were making a fetch request, that redirection is not reflected in your client end
you need to use router.push() inside your useEffect()
after the fetch
Norwegian BuhundOP
router from next/router?
@Norwegian Buhund router from next/router?
Sun bear
yeah.
Norwegian BuhundOP
ok it works
thank you both
great to help you!
mark solution to close the thread! 🙂
Norwegian BuhundOP
how?
Original message was deleted
@Norwegian Buhund
try this to the most appropriate message that answers your problem