Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NextJs - Where can we add a <script> code?

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?

like image 426
Shruthi R Avatar asked Apr 21 '21 05:04

Shruthi R


1 Answers

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>
    </>
  )
}
like image 125
Dennis Vash Avatar answered Oct 21 '22 19:10

Dennis Vash