カスタムドキュメント
カスタム Document を使用することで、Page のレンダリングに使用される <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など)をここに追加しないでください。すべてのページで共有されるコンポーネント(メニューやツールバーなど)が必要な場合は、代わりに Layouts を参照してください。Documentは現在のところ、getStaticPropsやgetServerSidePropsなどの Next.js Data Fetching メソッドをサポートしていません。
renderPage のカスタマイズ
renderPage のカスタマイズは高度な機能であり、CSS-in-JS のようなライブラリでサーバーサイドレンダリングをサポートする場合にのみ必要です。組み込みの styled-jsx サポートには必要ありません。
このパターンの使用はお勧めしません。 代わりに、段階的に採用する App Router の導入を検討してください。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,
})
// 親の `getInitialProps` を実行します。これでカスタム `renderPage` が含まれます
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オブジェクトは、getInitialPropsで受け取るオブジェクトと同等ですが、renderPageが追加されています。