Introduction
When trying to implement page navigation using router.push("/")
,
you may encounter the following error:
Unhandled Runtime Error
Error: NextRouter was not mounted.
Environment
- next: 14.0.3
Solution
This error is caused by a change in the useRouter
import path starting from Next.js v13.
Previously, we used:
import { useRouter } from 'next/router'
But from v13 onwards, it should be:
import { useRouter } from 'next/navigation';
Other than the import path, the rest of the code remains the same:
import { useRouter } from 'next/navigation';
const App = () => {
const router = useRouter();
const click = () => {
router.push("/")
}
return (
<></>
)
}
export default App;
Conclusion
If you forget, you might still use next/router
.
Always refer to the official documentation.
Even when searching online or using ChatGPT, the information is often based on versions prior to v13 and may not be correct.
References
https://nextjs.org/docs/app/api-reference/functions/use-pathname
https://stackoverflow.com/questions/74421327/nextrouter-was-not-mounted-next-js