Search code examples
javascriptnext.jsamplitude-analytics

NextJS Script tag not loading amplitude


I have following code to include amplitude js for tracking using Script tag. But, amplitude is not loading events.

import Document, { Html, Head, Main, NextScript } from 'next/document';
import Script from 'next/script';
          <Html lang="en">
                <Head>
                     <Script
                        async
                        key="amplitude"
                        src="/js/analytics/amplitude.js"
                    ></Script>

               </Head>
          </Html>

amplitude.js has following code which includes amplitude using SDK way here

(function(e,t){var n=e.amplitude||{_q:[],_iq:{}};var r=t.createElement("script")
;r.type="text/javascript"
;r.integrity="sha384-MBHPie4YFudCVszzJY9HtVPk9Gw6aDksZxfvfxib8foDhGnE9A0OriRHh3kbhG3q"
;r.crossOrigin="anonymous";r.async=true
;r.src="https://cdn.amplitude.com/libs/amplitude-8.16.1-min.gz.js"
;r.onload=function(){if(!e.amplitude.runQueuedFunctions){console.log(
"[Amplitude] Error: could not load SDK")}};var s=t.getElementsByTagName("script"
)[0];s.parentNode.insertBefore(r,s);function i(e,t){e.prototype[t]=function(){
this._q.push([t].concat(Array.prototype.slice.call(arguments,0)));return this}}
var o=function(){this._q=[];return this};var a=["add","append","clearAll",
"prepend","set","setOnce","unset","preInsert","postInsert","remove"];for(
var c=0;c<a.length;c++){i(o,a[c])}n.Identify=o;var l=function(){this._q=[]
;return this};var u=["setProductId","setQuantity","setPrice","setRevenueType",
"setEventProperties"];for(var p=0;p<u.length;p++){i(l,u[p])}n.Revenue=l;var d=[
"init","logEvent","logRevenue","setUserId","setUserProperties","setOptOut",
"setVersionName","setDomain","setDeviceId","enableTracking",
"setGlobalUserProperties","identify","clearUserProperties","setGroup",
"logRevenueV2","regenerateDeviceId","groupIdentify","onInit","onNewSessionStart"
,"logEventWithTimestamp","logEventWithGroups","setSessionId","resetSessionId",
"getDeviceId","getUserId","setMinTimeBetweenSessionsMillis",
"setEventUploadThreshold","setUseDynamicConfig","setServerZone","setServerUrl",
"sendEvents","setLibrary","setTransport"];function v(t){function e(e){
t[e]=function(){t._q.push([e].concat(Array.prototype.slice.call(arguments,0)))}}
for(var n=0;n<d.length;n++){e(d[n])}}v(n);n.getInstance=function(e){e=(
!e||e.length===0?"$default_instance":e).toLowerCase();if(
!Object.prototype.hasOwnProperty.call(n._iq,e)){n._iq[e]={_q:[]};v(n._iq[e])}
return n._iq[e]};e.amplitude=n})(window,document);

amplitude.getInstance().init("YOUR_API_KEY_HERE")

Using normal script tag is working fine though.


Solution

  • You can use <Head> tag on any page - it will automatically set <Head> to it. Don't need to modify _document or App. We expose a built-in component for appending elements to the head of the page: (link)

    And about the script - I had the same problem. My solution (possible bad)

    Inside your component (for script needs to be refreshed):

         useEffect(() => {
          
          const srcUrl = `/js/analytics/amplitude.js`;
          
          const s = document.createElement('script');
              const addScript = src => {
                s.setAttribute('src', src);
                s.setAttribute('async', 'async');
                s.setAttribute('defer', 'defer');
                s.setAttribute('id', 'specific_id')
                document.body.append(s);
                s.remove()
              };
            addScript(srcUrl)
    
    
          
        },[]);
    

    Or in App(for "static" scripts):

    const App = ({ Component, pageProps }) => (
      <>
        <Script
          src="/js/analytics/amplitude.js"
          strategy="beforeInteractive"
        />
    
        <Component {...pageProps} />
      </>
    );