Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next.js throwing Error: Error: NextRouter was not mounted when using _document.js inside pages folder

I want to be able to customize the HTML based on the current locale. I have created a _document.js inside pages directory. And I used this code:

import { Html, Head, Main, NextScript } from 'next/document'
import { useRouter } from 'next/router'

export default function Document() {
  
  const { locale } = useRouter();

  return (
    <Html>
      <Head />
      <body>
        <Main />
        <NextScript />
      </body>
    </Html>
  )
}

But I get this error:

Error: Error: NextRouter was not mounted. https://nextjs.org/docs/messages/next-router-not-mounted

When I go to the URL specified, I see them saying that I'm using logic outside <Main />. Thus, how can I access locale inside _document.js?

I found NextRouter was not mounted Next.JS but even using next/navigation did not work for me, and I get this error:

Error: invariant expected app router to be mounted

like image 949
behnam rahmani Avatar asked Sep 01 '25 10:09

behnam rahmani


1 Answers

It happened to me in the client component of app directory.

Instead of this

import { useRouter } from 'next/router'

import from

import { useRouter } from "next/navigation";
like image 119
Yilmaz Avatar answered Sep 04 '25 00:09

Yilmaz