DEV Community

Edih Goodluck
Edih Goodluck

Posted on

How To Add External Scripts in NextJS

Introduction

When working with ReactJS only if we needed to add an external script it's quite easy we can just add a script tag in the main index.html file and then it works most of the time but then when it comes to NextJS, there is no HTML file we can add the script to, so how do we add it? So let us dive into the solution.

How To Fix it
Using a normal script tag in the Head component will give warnings and won't work so instead, we use a component that is built into NextJS which is the Script Component. This component mimics the behavior of the script tag and you do not have to add it to the head you can add it to any page component to use it, and we can import it from NextJS using this format

import Script from "next/script"
Enter fullscreen mode Exit fullscreen mode

it has props which are existing attributes on the normal script tag example

import Script from "next/script";
import SomeComponent from "next/script";

const HomePage=()=>{
  return (
     <div>
       <Script 
        type="text/javascript" 
        id="hs-script-loader" 
        async 
        defer 
        src="//link-to-external-js"
       />
      <SomeComponent/>
     </div>
   )
}

export Homepage
Enter fullscreen mode Exit fullscreen mode

so the Javascript can now be loaded on the page and you can be able to use the javascript functions and variables.
To know more about this component you can visit this link https://nextjs.org/docs/api-reference/next/script

Thanks For Reading 😊😊😊😊😊

Top comments (1)

Collapse
 
felixrunquist profile image
Felix

Great post! Next.js definitely has a new take on importing scripts. It also has a specific Style component which I had trouble with when I started with the framework 2 years ago!