• Live group demo of Marketing Hub + Data Agent

    Standardize reporting, reduce manual work, and introduce AI without cleanup

    Join us on March 12
  • Ready to build your local HubSpot community?

    HUG leaders host events, spark connections, and create spaces where people learn and grow together.

    Become a HUG Leader

Next.js tracking code installation

IEvans
Member

I have been trying to embed the tracking code snippet into my site but I'm unsure how to do this in next.js. If anyone has advice on how to do this for next.js that would be much appreciated.

 

The tracking code installation information I am following is here:

https://knowledge.hubspot.com/reports/install-the-hubspot-tracking-code

 

1 Accepted solution
PatOfCle
Solution
Contributor

Thanks for the response, but this is not 100% accurate. For the Tracker component that you refer to, the version I show below should be in line with the most recent documentation: 

 
"use client"

import { useEffect, useRef } from 'react';
import { usePathname, useSearchParams } from 'next/navigation';

const HubspotTracker = () => {

const pathname = usePathname()
const searchParams = useSearchParams()
const searchParamsDict = Object.fromEntries(searchParams ? searchParams.entries() : [])

const emailAddress = searchParamsDict.email ? searchParamsDict.email : null

var firstLoad = useRef(true);

useEffect(() => {
 
if (typeof window !== 'undefined') {
var _hsq = window._hsq = window._hsq || [];
 
if (firstLoad.current === true) {
 
_hsq.push(['setPath', pathname]);
_hsq.push(['trackPageView']);

if (emailAddress) {
_hsq.push(["identify",{
email: emailAddress
}]);
}

// I think we only need the trackPageView entry once before the identify.
_hsq.push(['setPath', pathname]);
_hsq.push(['trackPageView']);

firstLoad.current = false
} else {

_hsq.push(['setPath', pathname]);
_hsq.push(['trackPageView']);

}
}
}, [pathname, searchParamsDict])

 
return null;
};

export default HubspotTracker;
 
 
Really just listing this code above for those who had same challenge as me.
 
I actually had it properly set up just like this for a while, but the tracker for some reason didn't work properly on localhost:3000 out of my dev environment. After deploying to main prod environment, it worked without an issue. Also be sure that you don't have any ad-blockers for this to work. 
 

View solution in original post

0 Upvotes
13 Replies 13
PatOfCle
Contributor

Any updates @IEvans ? Did this end up working? Trying to do this myself with NextJS. Unsure if it being Server-Side Rendered affects how/when the scripts run...

Any help would be appreciated here!

0 Upvotes
FAbdalla
Member

Hi, @PatOfCle 

 

########Installation########


To embed the HubSpot tracking code snippet in your Next.js application, you can follow these steps:

1. **Sign Up for HubSpot**:
   If you haven't already, sign up for a HubSpot account and create a new tracking code snippet from your HubSpot dashboard.

2. **Install HubSpot npm Package**:
   HubSpot provides an npm package for easier integration with Next.js. Install it using npm or yarn:

   ```bash
   npm install @hubspot/tracking-code
   # or
   yarn add @hubspot/tracking-code
   ```

3. **Create a HubSpot Tracking Component**:
   Create a new component to manage the HubSpot tracking code. You can put this component in a file like `HubSpotTracking.js`:

   ```jsx
   // components/HubSpotTracking.js
   import { useEffect } from 'react';
   import { useRouter } from 'next/router';

   const HubSpotTracking = () => {
     const router = useRouter();

     useEffect(() => {
       if (window.hbspt) {
         window.hbspt.initialize('YOUR_HUBSPOT_PORTAL_ID');
       }
       router.events.on('routeChangeComplete', () => {
         if (window.hbspt) {
           window.hbspt.trackPageView();
         }
       });
     }, []);

     return null;
   };

   export default HubSpotTracking;
   ```

   Replace `'YOUR_HUBSPOT_PORTAL_ID'` with your actual HubSpot portal ID.

4. **Include the HubSpot Tracking Component**:
   Add the `HubSpotTracking` component to your layout or specific pages where you want HubSpot tracking to be enabled. For example, in your layout component:

   ```jsx
   // components/Layout.js
   import HubSpotTracking from './HubSpotTracking';

   const Layout = ({ children }) => (
     <div>
       <header>...</header>
       <main>{children}</main>
       <footer>...</footer>
       <HubSpotTracking />
     </div>
   );

   export default Layout;
   ```

5. **Deploy Your Site**:
   Deploy your Next.js application, and the HubSpot tracking code will be included in your site's HTML.

6. **Test and Verify**:
   After deployment, test the tracking to ensure it's working as expected. Visit different pages on your site to make sure HubSpot is tracking your analytics data.

This implementation assumes that you have access to your HubSpot portal ID and the appropriate permissions to use the tracking code. Be sure to replace `'YOUR_HUBSPOT_PORTAL_ID'` with your actual HubSpot portal ID from your HubSpot account.

Remember to refer to HubSpot's official documentation for any specific instructions or updates regarding their tracking code implementation.

0 Upvotes
PatOfCle
Contributor

Thank you regardless, though, for the reply.

0 Upvotes
PatOfCle
Solution
Contributor

Thanks for the response, but this is not 100% accurate. For the Tracker component that you refer to, the version I show below should be in line with the most recent documentation: 

 
"use client"

import { useEffect, useRef } from 'react';
import { usePathname, useSearchParams } from 'next/navigation';

const HubspotTracker = () => {

const pathname = usePathname()
const searchParams = useSearchParams()
const searchParamsDict = Object.fromEntries(searchParams ? searchParams.entries() : [])

const emailAddress = searchParamsDict.email ? searchParamsDict.email : null

var firstLoad = useRef(true);

useEffect(() => {
 
if (typeof window !== 'undefined') {
var _hsq = window._hsq = window._hsq || [];
 
if (firstLoad.current === true) {
 
_hsq.push(['setPath', pathname]);
_hsq.push(['trackPageView']);

if (emailAddress) {
_hsq.push(["identify",{
email: emailAddress
}]);
}

// I think we only need the trackPageView entry once before the identify.
_hsq.push(['setPath', pathname]);
_hsq.push(['trackPageView']);

firstLoad.current = false
} else {

_hsq.push(['setPath', pathname]);
_hsq.push(['trackPageView']);

}
}
}, [pathname, searchParamsDict])

 
return null;
};

export default HubspotTracker;
 
 
Really just listing this code above for those who had same challenge as me.
 
I actually had it properly set up just like this for a while, but the tracker for some reason didn't work properly on localhost:3000 out of my dev environment. After deploying to main prod environment, it worked without an issue. Also be sure that you don't have any ad-blockers for this to work. 
 
0 Upvotes
ASELLAMI
Participant

Hello , 
can u please explain more like where to paste the snippet of hubspot tracking code ??
and where to use HubspotTracker that u created ??

0 Upvotes
PatOfCle
Contributor

The tracking code code I pasted above is in a component <HubspotTracker />. 

I then call add that component to my layout.js file at the top level of my app router in the src/app/ directory.

 

Here is my code for that layout.js file:


import { Inter } from 'next/font/google'
const inter = Inter({ subsets: ['latin'] })

import './globals.css'
import Header from '@/components/Header/Header'
import Footer from '@/components/Footer/Footer'
import HubspotTracker from '@/components/HubspotStuff/HubspotTracker'
import ScrollToTop from '@/components/Misc/ScrollToTop'
import Script from 'next/script'
import { Suspense } from 'react'


import { Analytics } from '@vercel/analytics/react';
import { SpeedInsights } from "@vercel/speed-insights/next"

export default function RootLayout({ children }) {

return (
<html lang="en">
<link rel="icon" href="/favicon.ico" sizes="any" />

<ScrollToTop />

 

<body className={inter.className}>
<Suspense>

<Header />
<div className='app-container'>
{children}
<Analytics />
<SpeedInsights />
</div>
<Footer />



{/* Script needs to be loaded here, right before the HubspotTracker component */}
<Script type="text/javascript" id="hs-script-loader" async defer src="//js.hs-scripts.com/[YOUR HUBSPOT ID HERE].js" strategy="beforeInteractive" />

<HubspotTracker />
</Suspense>

</body>
</html>
)
}

 



IMPORTANT: For some reason, the tracker did not work when I was testing on localhost. However, when I deployed the app with the tracking code, tracking worked on my public domain. I believe this difference in outcomes (the tracking code not working local but working once deployed) has something to do with atypical SSR happening (especially the timing of when the code is actually embedded with respect to the client) when testing on localhost. 

 

Hope this helps.

ASELLAMI
Participant

Thank you so much for your reply

0 Upvotes
PatOfCle
Contributor

@Jaycee_Lewis One other thing: Next.js came out with their new App Router... it looks like your solution is for the Next v13 and earlier Pages Router. Any clue how to do this with the App Router?

Also, curious where you did the research for this solution? Any helpful resources for me?

0 Upvotes
Jaycee_Lewis
Thought Leader

Hi, @IEvans 👋 Thanks for reaching out! Let's see if the community has any experience here — hey @Teun @MatthiasWeber, do you have a simple example you can share with @IEvans? I am not too familiar with this framework and would love another brain or two here. 

 

Here's what I found:

  • Create a new file called hubspot.js in the pages directory and paste your HubSpot tracking code into this file:
    import React from 'react';
    
    const Hubspot = () => {
      return (
        <>
          <script type="text/javascript" id="hs-script-loader" async defer src="//js.hs-scripts.com/<your-hubspot-id>.js"></script>
          <script
            dangerouslySetInnerHTML={{
              __html: `
                hs.beacon.ready(function() {
                  hs.beacon.identify({
                    ...
                  });
                });
              `,
            }}
          />
        </>
      );
    };
    
    export default Hubspot;​
  • In your pages/_app.js file, import the Hubspot component and render it at the end of the <Head> component:
    import Head from 'next/head';
    import Hubspot from './hubspot';
    
    function MyApp({ Component, pageProps }) {
      return (
        <>
          <Head>
            ...
          </Head>
          <Component {...pageProps} />
          <Hubspot />
        </>
      );
    }
    
    export default MyApp;​

*Please note, this is an amalgamation of research I did for this topic. And may not be best practices.*

 

Thanks for taking a look! — Jaycee





loop


Loop Marketing is a new four-stage approach that combines AI efficiency and human authenticity to drive growth.

Learn More




CWizard
Member

Hi, I'm a new here. I have to implement the tracking codes to my Next.js app.

Can you tell me what is it for and how can I check if the tracking code is implemented to my app?
Actually I wrote the codes of yours but I don't know what happened.

Please let me know how it will work.

Thank you

0 Upvotes
ASELLAMI
Participant

any news about your work i'm also new and didn't know how to  implement the tracking codes to my Next.js app ,
can u please share ur steps with me ?

0 Upvotes
nop1984
Member

that doesn't solve and has no benefits over Script from 'next/script'

Cannot identify portalId of loaded script. No elements matching `script[data-hsjs-portal]` found on page

 

0 Upvotes
MatthiasWeber
Guide

Looks good @Jaycee_Lewis , i would say. does it works @IEvans ?

 

Cheers Matt