Next.js is a popular React framework for building web applications. One of its core features is Server Side Rendering (SSR). However, in some cases, SSR can create duplicated traffic data from your website on Cyan Stats.

Preventing duplicated entries

Although the Cyan Stats tracking script already implements a technique to prevent server-side rendered pages from calling the tracking API while not loaded on the client-side, the following Next.js/React component will make it work even smoother! ๐Ÿค—

The component

Create a new component called cyanstats.tsx at your preferred component location. In this brand new component, paste the code below and save.

// cyanstats.tsx

'use client'

import { useEffect } from 'react';

interface CyanStatsProps {
  token?: string;
}

const CyanStats: React.FC<CyanStatsProps> = ({ token }) => {
  useEffect(() => {
    if (typeof window !== 'undefined') {
      const script: any = document.createElement('script');

      script.src = '<https://cyanstats.com/cs.js>';
		  script.async = true;

      if (token) {
        script.setAttribute('data-token', token);
      }

      document.head.appendChild(script);
    }
  }, []);

  return <div></div>;
};

export default CyanStats;

Next, import the newly created component into the layout.tsx or any other file that fits better. The file youโ€™re gonna import CyanStats into depends on how your project is organized.

E.g๐Ÿ‘‡

// layout.tsx

import CyanStats from './path/to/components/CyanStats';

// ...

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en">
      <body>
        {children}
        <CyanStats token="..." />
      </body>
    </html>
  )
}

<aside> โ˜ Passing the token is optional in production, when calling Cyan Stats from the same domain registered to your project. But, it will help you see if itโ€™s working while in development.

Your token can be retrieved in the settings page.

</aside>

Done! ๐Ÿ‘