Next.jsMedium

What is the _document.js file and when should you use it?

pages/_document.js customizes the server-rendered <html>, <head> and <body> shell in the Pages Router. Use it for the lang attribute, body classes or CSS-in-JS server setup. In the App Router, the root app/layout.tsx does this job directly.

Key facts

  • It renders only on the server, once per request or build. It never runs in the browser.
  • Event handlers such as onClick and React state do not work here.
  • It must render <Html>, <Head>, <Main> and <NextScript> from next/document.
  • The <Head> from next/document is for tags shared by all pages. Page titles and meta tags belong in next/head inside pages.

When to use it

  • Setting <Html lang="en"> or classes on <body>.
  • Collecting server-rendered styles for libraries such as styled-components or Emotion (via getInitialProps).
  • Adding <link> preconnects or font tags that every page needs.

When not to use it

  • Do not put application logic, data fetching or providers here; use _app.
  • Do not load third-party scripts with raw tags; use next/script with strategy="beforeInteractive" if it must run early.

App Router equivalent

The root layout renders the document yourself, so there is no separate file. Fonts come from next/font, metadata from the Metadata API, and CSS-in-JS setup uses a registry with useServerInsertedHTML.

Code example

tsx
1// pages/_document.tsx
2import { Html, Head, Main, NextScript } from "next/document";
3
4export default function Document() {
5 return (
6 <Html lang="en">
7 <Head>
8 {/* Shared tags only. Titles go in next/head per page. */}
9 <link rel="preconnect" href="https://cdn.example.com" />
10 </Head>
11 <body className="antialiased">
12 <Main />
13 <NextScript />
14 </body>
15 </Html>
16 );
17}
18
19// App Router: app/layout.tsx does the same thing directly
20// export default function RootLayout({ children }: { children: React.ReactNode }) {
21// return (
22// <html lang="en">
23// <body className="antialiased">{children}</body>
24// </html>
25// );
26// }

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.

Open in study app