9

In NextJs application, I want to add <script> code but not getting where to add and how? I tried by adding it in .js file but didn't recognise.

In react, we have index.html to add these things, what about in Nextjs app?

2
  • take a look at this Next.js Loads <script> tags but it doesn't execute them Commented Apr 21, 2021 at 5: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) Commented Apr 21, 2021 at 6:00

1 Answer 1

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>
    </>
  )
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.