Next.js › Custom App & Document in Pages Router

What is the custom Document component used for in the Pages Router?

Beginner

Answer

The custom Document component, defined in pages/_document.js, controls the initial HTML structure of your page, such as the html and body tags, and is the right place to add things like custom fonts, a language attribute, or third party scripts that need to load in the head or body.
// pages/_document.js
import { Html, Head, Main, NextScript } from 'next/document';

export default function Document() {
  return (
    <Html lang="en">
      <Head />
      <body>
        <Main />
        <NextScript />
      </body>
    </Html>
  );
}
Real-world example A multilingual website sets the correct lang attribute on the html tag inside its custom Document component, helping search engines and screen readers understand the page's primary language.

Common follow-ups: What is the difference between the custom App and custom Document components?;Can you use React state or hooks inside the custom Document component?