behnam rahmani
behnam rahmani

Reputation: 61

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

Upvotes: 4

Views: 8348

Answers (2)

Youssouf Oumar
Youssouf Oumar

Reputation: 46261

useRouter() hook runs on the browser while _document.js runs on the server; that's the problem. For example, if you add a console.log('Hello Word') in Document before the return, it gets printed only in your development server, not on the browser.

You shouldn't be trying to use a logic related to hooks in _document.js, as it's not meant for, as the doc says:

React components outside of <Main /> will not be initialized by the browser. Do not add application logic here or custom CSS (like styled-jsx). If you need shared components in all your pages (like a menu or a toolbar), read Layouts instead.

Upvotes: 3

Yilmaz
Yilmaz

Reputation: 49709

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";

Upvotes: 10

Related Questions