NextJs - Where can we add a – Ravikumar Apr 21 '21 at 05:56

  • @Ravikumar notice that the answer in shared link will execute script only on index page (if the user enters from other path, it wont be executed) – Dennis Vash Apr 21 '21 at 06:00
  • 1 Answers1

    9

    To edit the index.html, the equivalent in NextJS is the _document.js file.

    A custom Document is commonly used to augment your application's <html> and <body> tags.

    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 />
              <NextScript />
              <script>...</script>
            </body>
          </Html>
        )
      }
    }
    

    If you only want to append elements to <head> tag (for a specific page), use next/head:

    import Head from 'next/head'
    
    function IndexPage() {
      return (
        <>
          <Head>
            <script>....</script>
          </Head>
        </>
      )
    }
    
    Dennis Vash
    • 50,196
    • 9
    • 100
    • 118