Reputation: 2877
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
Reputation: 1819
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
Reputation: 46604
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'
}
]
},
app.html
at the root of your project<html {{ HTML_ATTRS }}>
<head>
{{ HEAD }}
</head>
<body {{ BODY_ATTRS }}>
{{ APP }}
<!--EXTRA JS FILES-->
</body>
</html>
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