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

How to load external JavaScript scripts

  • If you are planning to import a .js file, I do recommend this article: https://vueschool.io/articles/vuejs-tutorials/how-to-load-third-party-scripts-in-nuxt-js/

  • Use inject to add an NPM package to Nuxt's context, this blog post by Alexander explains it even further

  • Josh Deltener has a great article on how to import it properly too (with various approaches!)

  • You could also use this solution in your nuxt.config.js file (it's not that bad as you can see in the github issues of Nuxt)

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.