Next.js Loads <script> tags but it doesn't execute them

This works to me:

Create a folder for your static files:

<root>/static/hello.js

in your index.js

<root>/pages/index.js

import Head from 'next/head';
import MyAwesomeComponent from '../components/mycomponent';

export default () => (
  <div>
    <Head>
      <script type="text/javascript" src="/static/hello.js"></script>
    </Head>
    <MyAwesomeComponent />
  </div>
)

Hope this help,

Regards


With the below approach you can easily put a script file's raw script text into a generated Next.js HTML page's <head> without screwing around with character escaping, formatting and general pretending that we aren't actually just building an HTML page in the end anyways.

There are many use cases you may want a script to run without going to network. Ex: 3rd party scripts, monitoring / analytics scripts that expect to be in the <head> without a separate network load. Many of these come minified, mangled, you-name-it and are just supposed to be copy, paste, move on with life.

Next.js makes this very hard pretending that everything with web development is magically React and Webpack all the time now (I wish right?)

The best developer experience way I've found is to do this:

_document.js

...
<Head>
  <script type="text/javascript" dangerouslySetInnerHTML={{ __html: process.env.rawJsFromFile }}></script>
</Head>
...

next.config.js

https://github.com/vercel/next.js/blob/canary/packages/next/next-server/server/config.ts#L33

module.exports = {
  env: {
    rawJsFromFile: fs.readFileSync('./rawJsFromFile.js').toString()
  }
}

rawJsFromFile.js

alert('Freedom!!!!!!!!!!!!!!!');
// and other 3rd party script junk, heck even minified JS is fine too if you need

Hope this saves someone from hours of frustration that I endured coming up with this...


You can also run js code this

          <script
            dangerouslySetInnerHTML={{
              __html: `
                      let a = 1;
                      functionCall();
                  `,
            }}
          ></script>