DEV Community

adambaialiev
adambaialiev

Posted on

How to edit the head tag in Next.js

Want to add some link or script tags in the head?
In this post I'm going to show how to edit the content of the head tag.

In Next.js we can do it by overriding the default Document;

Create the file pages/_document.js and extend the Document class.

In render method we return the actual structure of the whole application tree. Don't put UI or business logic here.

In this examples, between the Head tag, I placed the link tags to Google fonts.

import Document, { Html, Head, Main, NextScript } from "next/document";

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

  render() {
    return (
      <Html>
        <Head>
          <link rel="preconnect" href="https://fonts.gstatic.com" />
          <link
            href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@300;400;600;700&display=swap"
            rel="stylesheet"
          />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

That's it!

Top comments (0)