Next.js
Integrate Databuddy with your Next.js application for server-side rendering support, automatic page tracking, and optimal performance.
Installation
Install the Databuddy SDK:
npm install @databuddy/sdkor with yarn:
yarn add @databuddy/sdkApp Router Setup (Next.js 13+)
1. Add Script Component to Layout
// app/layout.tsx
import { Databuddy } from '@databuddy/sdk/react';
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body>
<Databuddy
clientId={process.env.NEXT_PUBLIC_DATABUDDY_CLIENT_ID!}
trackHashChanges
trackAttributes
/>
{children}
</body>
</html>
);
}2. Track Route Changes (Optional)
If you need custom route tracking:
// app/analytics.tsx
'use client';
import { useEffect } from 'react';
import { usePathname, useSearchParams } from 'next/navigation';
import { track } from '@databuddy/sdk';
export function Analytics() {
const pathname = usePathname();
const searchParams = useSearchParams();
useEffect(() => {
const url = pathname + searchParams.toString();
track('screen_view', {
screen_name: pathname,
screen_class: 'Next.js',
url: url
});
}, [pathname, searchParams]);
return null;
}Then add to your root layout:
// app/layout.tsx
import { Databuddy } from '@databuddy/sdk/react';
import { Analytics } from './analytics';
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body>
<Databuddy
clientId={process.env.NEXT_PUBLIC_DATABUDDY_CLIENT_ID!}
/>
{children}
<Analytics />
</body>
</html>
);
}Pages Router Setup (Next.js 12 and below)
1. Add to _app.tsx
// pages/_app.tsx
import type { AppProps } from 'next/app';
import { Databuddy } from '@databuddy/sdk/react';
import { useRouter } from 'next/router';
import { useEffect } from 'react';
import { track } from '@databuddy/sdk';
function MyApp({ Component, pageProps }: AppProps) {
const router = useRouter();
useEffect(() => {
const handleRouteChange = (url: string) => {
track('screen_view', {
screen_name: url,
screen_class: 'Next.js'
});
};
router.events.on('routeChangeComplete', handleRouteChange);
return () => {
router.events.off('routeChangeComplete', handleRouteChange);
};
}, [router.events]);
return (
<>
<Databuddy
clientId={process.env.NEXT_PUBLIC_DATABUDDY_CLIENT_ID!}
trackAttributes
/>
<Component {...pageProps} />
</>
);
}
export default MyApp;Alternative: Manual Script in _document.tsx
If you prefer to add the script manually:
// pages/_document.tsx
import { Html, Head, Main, NextScript } from 'next/document';
export default function Document() {
return (
<Html lang="en">
<Head>
<script
src="https://cdn.databuddy.cc/databuddy.js"
data-client-id={process.env.NEXT_PUBLIC_DATABUDDY_CLIENT_ID}
async
/>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}Environment Variables
Add to your .env.local:
NEXT_PUBLIC_DATABUDDY_CLIENT_ID=your_client_id_hereFor production, add to your deployment environment:
NEXT_PUBLIC_DATABUDDY_CLIENT_ID=your_production_client_idTracking Events
Client-Side Tracking
// components/Button.tsx
import { track } from '@databuddy/sdk';
export function Button() {
const handleClick = () => {
track('button_click', {
button_text: 'Subscribe',
location: 'header'
});
};
return (
<button onClick={handleClick}>
Subscribe
</button>
);
}API Routes Integration
Track API usage and performance:
// pages/api/users.ts or app/api/users/route.ts
import { NextRequest, NextResponse } from 'next/server';
export async function GET(request: NextRequest) {
const startTime = Date.now();
try {
const users = await fetchUsers();
const duration = Date.now() - startTime;
// Note: Server-side tracking would require separate implementation
// This is client-side only SDK
return NextResponse.json(users);
} catch (error) {
return NextResponse.json({ error: 'Failed to fetch users' }, { status: 500 });
}
}E-commerce Integration
Track Purchases
// app/checkout/success/page.tsx
'use client';
import { useEffect } from 'react';
import { useSearchParams } from 'next/navigation';
import { track } from '@databuddy/sdk';
export default function CheckoutSuccess() {
const searchParams = useSearchParams();
useEffect(() => {
const orderId = searchParams.get('order_id');
const amount = searchParams.get('amount');
if (orderId && amount) {
track('purchase', {
transaction_id: orderId,
value: parseFloat(amount),
currency: 'USD'
});
}
}, [searchParams]);
return <div>Thank you for your purchase!</div>;
}Configuration Options
Advanced Configuration
You can configure Databuddy with various options:
// app/layout.tsx
import { Databuddy } from '@databuddy/sdk/react';
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body>
<Databuddy
clientId={process.env.NEXT_PUBLIC_DATABUDDY_CLIENT_ID!}
// Core tracking
trackHashChanges
// Interaction tracking
trackAttributes
trackOutgoingLinks
trackInteractions
// Performance tracking
trackPerformance
trackWebVitals
// Optimization
enableBatching
batchSize={10}
batchTimeout={2000}
// Development
disabled={process.env.NODE_ENV !== 'production'}
/>
{children}
</body>
</html>
);
}Conditional Loading
Only load in production:
// app/layout.tsx
import { Databuddy } from '@databuddy/sdk/react';
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body>
{process.env.NODE_ENV === 'production' && (
<Databuddy
clientId={process.env.NEXT_PUBLIC_DATABUDDY_CLIENT_ID!}
trackAttributes
/>
)}
{children}
</body>
</html>
);
}Vercel Integration
Vercel Analytics Replacement
Replace Vercel Analytics with Databuddy for better privacy:
// Before (with Vercel Analytics)
import { Analytics } from '@vercel/analytics/react';
// After (with Databuddy)
import { Databuddy } from '@databuddy/sdk/react';Environment Variables on Vercel
- Go to your Vercel project settings
- Add environment variable:
NEXT_PUBLIC_DATABUDDY_CLIENT_ID - Set different values for preview and production environments
Troubleshooting
Common Issues
Script Not Loading: Ensure your environment variable NEXT_PUBLIC_DATABUDDY_CLIENT_ID is set correctly.
Events Not Tracking: Check browser console for any JavaScript errors and verify the Databuddy script is loaded.
Route Tracking: If using custom route tracking, make sure the Analytics component is properly added to your layout.
Related Integrations
TypeScript support with React hooks and components.
Full SvelteKit support with SSR and automatic route tracking.
Payment tracking for comprehensive conversion analytics.
Need help with your Next.js integration? Contact us at help@databuddy.cc.
How is this guide?