Analytics15 min read
Integrating Analytics and CRM: Google Analytics, PostHog, and HubSpot
Complete guide to integrating analytics platforms and CRM systems into web applications for data-driven decision making.
Integrating analytics and CRM systems is essential for understanding user behavior, tracking conversions, and managing customer relationships. This guide covers implementing Google Analytics, PostHog, and HubSpot in Next.js applications.
Setting Up Google Analytics
Installation and Configuration
typescript
// lib/analytics.ts
export const GA_TRACKING_ID = process.env.NEXT_PUBLIC_GA_ID;
export const pageview = (url: string) => {
if (typeof window !== 'undefined' && window.gtag) {
window.gtag('config', GA_TRACKING_ID, {
page_path: url,
});
}
};
export const event = ({
action,
category,
label,
value,
}: {
action: string;
category: string;
label?: string;
value?: number;
}) => {
if (typeof window !== 'undefined' && window.gtag) {
window.gtag('event', action, {
event_category: category,
event_label: label,
value: value,
});
}
};Next.js Integration
typescript
// app/layout.tsx
import Script from 'next/script';
export default function RootLayout({ children }) {
return (
<html>
<head>
<Script
strategy="afterInteractive"
src={`https://www.googletagmanager.com/gtag/js?id=${GA_TRACKING_ID}`}
/>
<Script id="google-analytics" strategy="afterInteractive">
{`
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${GA_TRACKING_ID}');
`}
</Script>
</head>
<body>{children}</body>
</html>
);
}Tracking Custom Events
typescript
// components/Button.tsx
import { event } from '@/lib/analytics';
export function CTAButton() {
const handleClick = () => {
event({
action: 'click',
category: 'engagement',
label: 'cta_button',
});
// Handle click
};
return <button onClick={handleClick}>Get Started</button>;
}Implementing PostHog
Setup
typescript
// lib/posthog.ts
import posthog from 'posthog-js';
if (typeof window !== 'undefined') {
posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY!, {
api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST,
loaded: (posthog) => {
if (process.env.NODE_ENV === 'development') posthog.debug();
},
});
}
export default posthog;Feature Flags
typescript
import posthog from '@/lib/posthog';
export function FeatureComponent() {
const isFeatureEnabled = posthog.isFeatureEnabled('new-feature');
if (!isFeatureEnabled) return null;
return <div>New Feature</div>;
}User Identification
typescript
// After user login
posthog.identify(userId, {
email: user.email,
name: user.name,
});HubSpot CRM Integration
HubSpot Forms
typescript
// components/HubSpotForm.tsx
'use client';
import { useEffect } from 'react';
export function HubSpotForm({ portalId, formId }: { portalId: string; formId: string }) {
useEffect(() => {
const script = document.createElement('script');
script.src = 'https://js.hsforms.net/forms/v2.js';
document.body.appendChild(script);
script.addEventListener('load', () => {
if (window.hbspt) {
window.hbspt.forms.create({
portalId,
formId,
target: '#hubspot-form',
});
}
});
return () => {
document.body.removeChild(script);
};
}, [portalId, formId]);
return <div id="hubspot-form" />;
}HubSpot API Integration
typescript
// app/api/hubspot/route.ts
export async function POST(request: Request) {
const { email, name } = await request.json();
const response = await fetch(
`https://api.hubapi.com/contacts/v1/contact/createOrUpdate/email/${email}`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${process.env.HUBSPOT_API_KEY}`,
},
body: JSON.stringify({
properties: [
{ property: 'email', value: email },
{ property: 'firstname', value: name },
],
}),
}
);
return Response.json(await response.json());
}Tracking Conversions
typescript
// Track conversion events
export function trackConversion(conversionType: string, value?: number) {
// Google Analytics
event({
action: 'conversion',
category: 'engagement',
label: conversionType,
value,
});
// PostHog
posthog.capture('conversion', {
type: conversionType,
value,
});
// HubSpot
fetch('/api/hubspot/track', {
method: 'POST',
body: JSON.stringify({ event: conversionType, value }),
});
}Privacy and GDPR Compliance
typescript
// Cookie consent management
export function CookieConsent() {
const [consent, setConsent] = useState(false);
const handleAccept = () => {
setConsent(true);
localStorage.setItem('cookie-consent', 'true');
// Initialize analytics
initializeAnalytics();
};
if (consent || localStorage.getItem('cookie-consent')) {
return null;
}
return <CookieBanner onAccept={handleAccept} />;
}Implement these integrations to gain valuable insights and manage customer relationships effectively.