カスタムドキュメント
カスタム Document
は、ページのレンダリングに使用される <html>
タグと <body>
タグを更新できます。
デフォルトの Document
をオーバーライドするには、以下のように pages/_document
ファイルを作成します:
pages/_document.tsx
TypeScript
import { Html, Head, Main, NextScript } from 'next/document'
export default function Document() {
return (
<Html lang="en">
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
補足:
_document
はサーバー上でのみレンダリングされるため、onClick
のようなイベントハンドラはこのファイルで使用できません。- ページを適切にレンダリングするには、
<Html>
、<Head />
、<Main />
、<NextScript />
が必要です。
注意点
_document
で使用される<Head />
コンポーネントは、next/head
のものとは異なります。ここで使用される<Head />
コンポーネントは、すべてのページで共通の<head>
コードにのみ使用する必要があります。<title>
タグなどその他のケースでは、ページやコンポーネントでnext/head
を使用することをお勧めします。<Main />
の外側のReactコンポーネントはブラウザによって初期化されません。アプリケーションロジックやカスタムCSS(styled-jsx
など)をここに追加しないでください。すべてのページで共有するコンポーネント(メニューやツールバーなど)が必要な場合は、代わりにレイアウトをお読みください。Document
は現在、getStaticProps
やgetServerSideProps
などのNext.jsのデータフェッチメソッドをサポートしていません。
renderPage
のカスタマイズ
renderPage
のカスタマイズは高度な操作で、CSS-in-JSのようなライブラリでサーバーサイドレンダリングをサポートする場合にのみ必要です。これは組み込みの styled-jsx
サポートには不要です。
このパターンの使用はお勧めしません。 代わりに、段階的に App Router を採用することを検討してください。これにより、ページとレイアウトのデータをより簡単にフェッチできます。
pages/_document.tsx
TypeScript
import Document, {
Html,
Head,
Main,
NextScript,
DocumentContext,
DocumentInitialProps,
} from 'next/document'
class MyDocument extends Document {
static async getInitialProps(
ctx: DocumentContext
): Promise<DocumentInitialProps> {
const originalRenderPage = ctx.renderPage
// Reactレンダリングロジックを同期的に実行
ctx.renderPage = () =>
originalRenderPage({
// 全Reactツリーをラップするのに便利
enhanceApp: (App) => App,
// ページごとにラップするのに便利
enhanceComponent: (Component) => Component,
})
// カスタム `renderPage` を含む親の `getInitialProps` を実行
const initialProps = await Document.getInitialProps(ctx)
return initialProps
}
render() {
return (
<Html lang="en">
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
}
export default MyDocument
補足:
_document
のgetInitialProps
はクライアントサイドの遷移中は呼び出されません。_document
のctx
オブジェクトは、renderPage
の追加を除いて、getInitialProps
で受け取るものと同等です。