Blog>
Snippets

Implementing a Custom Document for Script Optimization

Show how to create a custom _document.js file to optimize the script loading strategy for client-side components in Next.js.
import Document, { Html, Head, Main, NextScript } from 'next/document';

class MyDocument extends Document {
  static async getInitialProps(ctx) {
    const initialProps = await Document.getInitialProps(ctx);
    return { ...initialProps };
  }

  render() {
    return (
      <Html>
        <Head />
        <body>
          <Main />
          {/* Here we will place the NextScript which is required for Next.js to function properly */}
          {/* We can defer the loading of this script to optimize the page loading performance */}
          <NextScript />
        </body>
      </Html>
    );
  }
}

export default MyDocument;
This code snippet creates a custom _document.js file in a Next.js project. The MyDocument class extends the default Document class and overrides the getInitialProps method to perform initial setup on server renders. This allows customization of the document's structure, allowing us to optimize script loading for the client-side components. The NextScript is rendered at the end of the body to maintain Next.js functionalities while potentially deferring the script loading to optimize page performance.