drake035
drake035

Reputation: 2877

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

I'm trying to add the snippet provided by Segment Analytics into nuxt.config.js but I'm getting the following error:

FATAL $config is not defined

What am I doing wrong?

nuxt.config.js:

head: {
  script: [
    {
      hid: 'segment-script',
      innerHTML: `
        !function(){var analytics=window.analytics=window.analytics||[];if(!analytics.initialize)...
        analytics.load(${this.$config.segmentApiSecret});
        analytics.page();
        }}();
      `,
      type: 'text/javascript',
      charset: 'utf-8'
    }
  ]
},
privateRuntimeConfig: {
  segmentApiSecret: process.env.SEGMENT_API_SECRET
},

Upvotes: 3

Views: 14065

Answers (2)

Romalex
Romalex

Reputation: 1819

2024 solution

There is actually a new convenient way of adding 3rd party scripts to Nuxt - Nuxt Scripts. It even has an out-of-the-box solution for google tag manager as well as some other popular third party scripts.

However it is still in beta and API may change in the future, so be carefull.

Upvotes: 0

kissu
kissu

Reputation: 46604

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.

Upvotes: 11

Related Questions