Resolved: Router.push(“/”) not working inside pages/index.js

In this post, we will see how to resolve Router.push(“/”) not working inside pages/index.js


I am using Next JS next-auth/react lib and want to redirect users who have authenticated status to dashboard. This is my index.js –
My pages/_app.js is –
NOTE – My index page does route to /dashboard/users but it displays blank and this error in console.
Also, when I refresh the route again, it displays the page just fine (/dashboard/users page is perfectly working but routing from index isn’t).
I simply want to redirect my logged in users to dashboard, but when I go to my index page, I get this error-

The above error occurred in the component: at Home (webpack-internal:///./src/pages/index.js:26:72) at SessionProvider (webpack-internal:///./node_modules/next-auth/react/index.js:417:24) at MyApp (webpack-internal:///./src/pages/_app.js:71:28) at ErrorBoundary (webpack-internal:///./node_modules/next/dist/compiled/@next/react-dev-overlay/client.js:8:20584) at ReactDevOverlay (webpack-internal:///./node_modules/next/dist/compiled/@next/react-dev-overlay/client.js:8:23125) at Container (webpack-internal:///./node_modules/next/dist/client/index.js:332:9) at AppContainer (webpack-internal:///./node_modules/next/dist/client/index.js:766:26) at Root (webpack-internal:///./node_modules/next/dist/client/index.js:883:27) React will try to recreate this component tree from scratch using the error boundary you provided, ErrorBoundary.

Best Answer:

You can try something like this.

If you have better answer, please add a comment about this, thank you!