How to add a 3rd party script code into Nuxt?

How to load external JavaScript scripts

head: {
  __dangerouslyDisableSanitizers: ['script'],
  script: [
    {
      hid: 'gtm-script1',
      src: 'https://www.googletagmanager.com/gtag/js?id=UA-111111111-1',
      defer: true
    },
    {
      hid: 'gtm-script2',
      innerHTML: `
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());

        gtag('config', 'UA-111111111-1');
      `,
      type: 'text/javascript',
      charset: 'utf-8'
    }
  ]
},
  • Otherwise, you can also add it to a app.html at the root of your project
<html {{ HTML_ATTRS }}>
   <head>
    {{ HEAD }} 
  </head>
  <body {{ BODY_ATTRS }}>
    {{ APP }}

    <!--EXTRA JS FILES-->
  </body>
</html>

Answer to the initial answer

If you’re adding it in the nuxt.config.js file, you need to directly use process.env.SEGMENT_API_SECRET.

May be a good idea to add this to some middleware or default layout than throwing directly some HTML into the config file.

Also, there is no point into adding it to privateRuntimeConfig if you are going to expose it anyway in the client. privateRuntimeConfig is only used for server operations while building the app (on the Node.js side). In your case, Segment will be totally public and hence, you should be fine with exposing your public API key (double-check still).


EDIT: other you could also use the official Nuxt or Vue plugin for this purpose.

Leave a Comment