Q9: What is pages/_document.js and how does it differ from pages/_app.js?

_document.js customizes the raw HTML document structure (<html>, <head>, <body>). It executes only on the server during initial rendering (never on the client). Do not use it for application state or event handlers.

Custom _document.js Structure
// 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>
  );
}
💡 Main renders active page markup; NextScript injects framework JavaScript scripts.
Key Takeaways
  • Customizes top-level <html>, <Head>, and <body> tags.
  • Executes strictly on the server; cannot attach client event listeners or React state.
Knowledge Check

Can you use React hooks like useState() inside pages/_document.js?