How to Integrate Plerdy Tracking Code into Your Next.js Website

Andrew Chornyy - 001
Andrew Chornyy

CEO Plerdy — expert in SEO&CRO with over 14 years of experience.

In this guide, we’ll walk you through the steps to seamlessly add Plerdy’s tracking code to your Next.js site.

Step 1: Create a Custom Script File

Firstly, you’ll need to create a new JavaScript file in your project. This file will contain the Plerdy tracking code. Name it something like PlerdyScript.js for easy identification.

Step 2: Insert the Plerdy Code

Open the PlerdyScript.js file and paste the Plerdy tracking code provided. Remember to wrap the code within a function to ensure it executes correctly. Here’s a snippet to illustrate:

export default function PlerdyScript() {
// Adding the Plerdy tracking code within the function
var _protocol = "https:" == document.location.protocol ? " https://" : " http://";
_site_hash_code = "dcb0945445500bc3511a17726f";
_suid = 34512;
var plerdyScript = document.createElement("script");
plerdyScript.setAttribute("defer", "");
plerdyScript.dataset.plerdymainscript = "plerdymainscript";
plerdyScript.src = "https://d.plerdy.com/public/js/click/main.js?v=" + Math.random();
var plerdymainscript = document.querySelector("[data-plerdymainscript='plerdymainscript']");
if (plerdymainscript) {
plerdymainscript.parentNode.removeChild(plerdymainscript);
}
try {
document.head.appendChild(plerdyScript);
} catch (t) {
console.log(t, "unable to add script tag");
}
}

Step 3: Import the Script in Your Pages

You need to import this script into the pages where you wish to track user interactions. This is typically done in a layout component or directly in specific pages. For example, in your _app.js file:

import PlerdyScript from './path/to/PlerdyScript';

Step 4: Execute the Script Using React’s useEffect Hook

Within the same file, use React’s useEffect hook to execute the script when the component mounts:

import { useEffect } from 'react';
function MyApp({ Component, pageProps }) {
useEffect(() => {
PlerdyScript();
}, []);
return <Component {...pageProps} />;
}

Once you’ve followed these steps, your Next.js website should be successfully integrated with Plerdy tracking. Ensure you test the implementation and verify that the script is loading correctly. Remember, analyzing user behavior is key to optimizing your site’s performance and enhancing user experience. Happy tracking!

Was this helpful?