How to redirect user outside of React component? #57495
Replies: 7 comments 3 replies
-
It's in https://nextjs.org/docs/app/api-reference/functions/use-router
|
Beta Was this translation helpful? Give feedback.
-
register it as callback to window object and call it from whatever you want :) |
Beta Was this translation helpful? Give feedback.
-
Can do the same in client-side |
Beta Was this translation helpful? Give feedback.
-
I'd like to implement redirection logic in my client fetch wrapper (intercepting some specific 4xx status codes that provide redirect url as payload), can't figure out any clean way of accessing the client side router - currently had to resolve it with a dirty workaround using window.location.. |
Beta Was this translation helpful? Give feedback.
-
I found this page yesterday when I had a similar issue.
My usage:
This is also contained in the docs. |
Beta Was this translation helpful? Give feedback.
-
Omg, I cannot believe it's still a problem in next/react unlike nuxt/vue where you can redirect outside of components |
Beta Was this translation helpful? Give feedback.
-
Just a heads-up for anyone else running into this: When you use router.push('/api/your-endpoint'), it first tries to fetch the route via client-side navigation (using fetch). But because it's an API route and not a Next.js page, the browser falls back to a full page reload (document). As a result, the API endpoint gets hit twice, which can be super confusing and frustrating to debug. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I'm migrating a project from CRA to Next.js 13 and the code often uses the
history.push('/')
methods and thereact-router
library, something similar is in Pages Router:But there is no such approach in App Router, only hooks. Is there a way to use the router outside of a React application?
Beta Was this translation helpful? Give feedback.
All reactions