Special files
_app.tsx and _document.tsx are two special files, that we may optionally provide. In absence, Next.js provides its own version of those files. They both live in pages/.
_app.tsx
It serves as a global wrapper: it matches every routes.
It is the designated file to import global stylesheets, which Next.js doesn't allow elsewhere:
import "../styles/global.css"
We may import and expose a local font: see Expose a local font.
We may use distinct favicons dynamically.
We must add some boilerplate: The file must have a default export and feed pageProps to Component.
export default function App({ Component, pageProps }: AppProps) {
return (
<>
<Component {...pageProps} />
</>
)
}
_document.tsx
It serves a limited role. Since we have control over the <html> element, we may add the lang attribute. We may also import Google fonts outside of Next.js control. Finally, we may also import a static favicon.
Next.js does not expose an index.html file. _document.tsx is the only place where we have direct control over the <html> and <body> elements, though technically we rely on <Html> and other Next.js provided wrappers, and the content we set in <Head> is not exhaustive.
import { Html, Head, Main, NextScript } from "next/document"
const FAVICON_URL = "/favicon.ico"
export default function Document() {
return (
<Html lang="en">
<Head>
<link
href="https://fonts.googleapis.com/css2?family=PT+Mono&display=swap"
rel="stylesheet"
/>
<link rel="icon" href={FAVICON_URL} />
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
)
}