Alytica Docs
Guides

NextJs

Integrate Alytica with your NextJs application.

1. Installation

npm install alytica-js

2. Create a Provider Component

Create components/AlyticaWrapper.tsx:

'use client';
import { AlyticaProvider } from 'alytica-js/react';
 
const alyticaConfig = {
  clientId: 'your-client-id',
  clientSecret: 'your-client-secret',
  debug: true,
  trackPageViews: true
};
 
export function AlyticaWrapper({ children }) {
  return (
    <AlyticaProvider options={alyticaConfig}>
      {children}
    </AlyticaProvider>
  );
}

3. Wrap Your App

In app/layout.tsx:

import { AlyticaWrapper } from '../components/AlyticaWrapper';
 
export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        <AlyticaWrapper>
          {children}
        </AlyticaWrapper>
      </body>
    </html>
  );
}

Best Practices

  • Use 'use client' directive for client-side components
  • Replace 'your-client-id' and 'your-client-secret' with your actual Alytica credentials
  • Configure tracking options based on your specific requirements
  • Ensure compliance with privacy regulations when tracking user data

Important: Page View Tracking in Next.js

Warning: Using the built-in trackPageViews option is not recommended for Next.js applications. Instead, implement manual page view tracking as shown below:

Create a PageViewTracker.tsx component:

"use client";
import { useEffect } from "react";
import { usePathname } from "next/navigation";
import { useAlytica } from "alytica-js/react";
 
export function PageViewTracker() {
  const pathname = usePathname();
  const alytica = useAlytica();
  
  useEffect(() => {
    // Track page view manually using the track method
    alytica.track("$pageview");
  }, [pathname, alytica]);
  
  return null;
}

Then add it to your root layout:

import { AlyticaWrapper } from '../components/AlyticaWrapper';
import { PageViewTracker } from '../components/PageViewTracker';
 
export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        <AlyticaWrapper>
          <PageViewTracker />
          {children}
        </AlyticaWrapper>
      </body>
    </html>
  );
}

This approach is necessary because Next.js uses client-side routing and the App Router, which don't trigger traditional page loads that the built-in tracking would detect. Manual tracking ensures accurate analytics as users navigate through your application.

On this page