Skip to main content
How to Add RB2B's Script to Next.js
Updated over a week ago

To ensure your RB2B tracking script fires on every page view in a Next.js application, you need to account for the client-side navigation behavior of Next.js, which uses React's useRouter and next/router for routing. JavaScript files added directly to index.html or _app.js will only load on the initial page load.

Here's how you can ensure the script is reloaded on every page view:

Step 1: Get Your Tracking Script ID

On the Script Setup page of the RB2B dashboard, you will find your RB2B tracking snippet which is normally used to install RB2B on your website. To execute Step 2 below, we only need to obtain your account's unique tracking script ID.

On the last line of the HTML snippet you'll see the following code:

reb2b.SNIPPET_VERSION = "1.0.1";reb2b.load("XXXXXXXXXXX");}();

XXXXXXXXXXX represents your unique tracking script ID. Copy your ID to your clipboard for use in Step 2 below.

Step 2: Using _app.js for Site-wide Script Execution

You can include the script directly within the _app.js file using the useEffect hook to ensure it executes once when the app component mounts. This method is suitable for scripts that don't need to manipulate the DOM immediately or rely on being present in the <head>.

Replace YOUR-UNIQUE-ID in the const SCRIPT_KEY with the ID obtained in Step 1.

import { useEffect } from 'react';
import { useRouter } from 'next/router';

function MyApp({ Component, pageProps }) {
const router = useRouter();

// Define the variable for the unique script identifier
const SCRIPT_ID = 'external-js-script';
const SCRIPT_BASE_URL = 'https://s3-us-west-2.amazonaws.com/b2bjsstore/b/';
const SCRIPT_KEY = 'YOUR-UNIQUE-ID'; // Update this value as needed
const SCRIPT_URL = `${SCRIPT_BASE_URL}${SCRIPT_KEY}/${SCRIPT_KEY}.js.gz`;

useEffect(() => {
const handleRouteChange = () => {
// Remove the script if it already exists
const existingScript = document.getElementById(SCRIPT_ID);
if (existingScript) {
existingScript.remove();
}

// Create and add the new script
const script = document.createElement('script');
script.id = SCRIPT_ID;
script.src = SCRIPT_URL;
script.async = true;
document.body.appendChild(script);
};

// Attach the handler to route changes
router.events.on('routeChangeComplete', handleRouteChange);

// Initial load
handleRouteChange();

// Clean up on component unmount
return () => {
router.events.off('routeChangeComplete', handleRouteChange);
};
}, [router.events, SCRIPT_URL]);

return <Component {...pageProps} />;
}

export default MyApp;

Explanation

  1. Route Change Handling:

    • router.events.on('routeChangeComplete', handleRouteChange) listens for route changes and triggers the script reload.

  2. Script Removal and Re-Addition:

    • If the script is already loaded, it is removed and re-added to ensure it fires again.

  3. Dynamic Script Loading:

    • A new <script> element is created dynamically and appended to the document's body.

  4. Initial Load:

    • The handleRouteChange function is invoked immediately for the initial load.

  5. Cleanup:

    • On component unmount, the event listener is removed to prevent memory leaks.

Testing

  • Ensure the script URL is reachable and the script works independently.

  • Check in both development and production modes of your Next.js app to verify the behavior.

Did this answer your question?