Next.js
Set up Human Behavior with Next.js applications
Quickstart
Human Behavior works seamlessly to record sessions on your Next.js app.
Step 1: Installation
npm install humanbehavior-js
# or
yarn add humanbehavior-jsStep 2: Environment Variables
Create an environment file (.env.local) with your API key:
NEXT_PUBLIC_HUMANBEHAVIOR_API_KEY=your-api-key-hereStep 3: Basic Setup
Create or edit existing app/providers.tsx:
'use client';
import { HumanBehaviorProvider } from 'humanbehavior-js/react';
...
export function HBProvider({ children }: { children: React.ReactNode }) {
return (
<HumanBehaviorProvider
apiKey={process.env.NEXT_PUBLIC_HUMANBEHAVIOR_API_KEY}
options={{
redactionStrategy: {
mode: 'visibility-first' as const
}
}}
>
{children}
</HumanBehaviorProvider>
);
}Update layout.tsx to use HBProvider
In app/layout.tsx:
import { HBProvider } from '@/app/providers';
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body>
<HBProvider>
{children}
</HBProvider>
</body>
</html>
);
}Why use a separate providers file? This pattern keeps your app layout as a Server Component while only making the provider client-side. This preserves the performance benefits of Server Components and ensures optimal rendering.
That's it! The SDK now automatically tracks user interactions, navigation, and console events. Everything past here is optional.
Alternative: Manual Initialization
If you prefer manual setup, you can initialize the tracker directly:
'use client'; // This line is CRUCIAL - it tells Next.js this is a client component
import { useEffect } from 'react';
import { HumanBehaviorTracker } from 'humanbehavior-js';
function MyApp({ Component, pageProps }) {
useEffect(() => {
// Initialize the tracker once globally
const tracker = HumanBehaviorTracker.init(process.env.NEXT_PUBLIC_HUMANBEHAVIOR_API_KEY);
}, []);
return <Component {...pageProps} />;
}
export default MyApp;Data Redaction
Configure data redaction for sensitive information in your providers:
export function Providers({ children }: ProvidersProps) {
return (
<HumanBehaviorProvider
apiKey={process.env.NEXT_PUBLIC_HUMANBEHAVIOR_API_KEY}
options={{
redactionStrategy: {
mode: 'privacy-first' as const,
unredactFields: ['#public-comment', '#feedback']
}
}}
>
{children}
</HumanBehaviorProvider>
);
}Markup-Driven Redaction
You can also use HTML attributes for redaction:
// These fields will be redacted in visibility-first mode
<input id="username" data-hb-redact="true" />
<input id="ssn" data-hb-redact="true" />Features
- Automatic route change tracking
- Server-side rendering compatible
- Works with both App and Pages Router
- Optimized bundle size
- Flexible data redaction with privacy-first and visibility-first modes
Troubleshooting
- Make sure you're using
'use client'at the top of your file - Check browser console for any error messages
- Verify your API key is correct
- Ensure the tracker is initialized before any user interaction