Analytics
This guide will help you set up analytics for your Next.js Supabase SaaS template. You can choose between Google Analytics with Google Tag Manager or PostHog to track user behavior and gather insights into product performance. Follow this step-by-step guide to configure your analytics solution and improve your SaaS application’s tracking capabilities.
Overview
In this section, we will guide you on how to set up analytics for your Next.js Supabase SaaS Template. We recommend using either Google Analytics with Tag Manager or PostHog for tracking user interactions and gaining insights into your SaaS product's performance.
Google Analytics with Google Tag Manager
Google Tag Manager is an effective way to manage and deploy analytics and marketing tags on your Next.js application without modifying the code frequently. This section will walk you through how to set up both Google Analytics and Google Tag Manager in your Next.js project.
Step 1: Google Tag Manager Setup
Create an account on Google Tag Manager.
Step 2: Install @next/third-parties.
Next.js has a built-in package to help manage third-party services like Google Tag Manager and Google Analytics efficiently. You can install the library with:
Step 3: Add Google Tag Manager to Next.js
Once installed, configure Google Tag Manager in your app/layout.tsx file (or _app.tsx):
Note: Replace GTM-XXXXXX with your Google Tag Manager ID.
Step 4: Connect Google Analytics via Google Tag Manager
Once Google Tag Manager is set up, you can configure Google Analytics within your Tag Manager account:
- Go to your Google Tag Manager account.
- Create a new tag, select "Google Analytics: GA4 Configuration."
- Enter your Google Analytics Measurement ID (e.g., G-XXXXXX).
- Set the trigger to "All Pages."
- Publish the changes.
This way, your Google Tag Manager is now connected to Google Analytics, and you can track events across your Next.js application.
PostHog Analytics
PostHog provides analytics and user tracking features for your SaaS application. Here’s how you can integrate PostHog in your Next.js project using the official provider pattern.
Step 1: Install PostHog Library
Install the official PostHog library for Next.js:
Step 2: Create a PostHog Provider Component
You will wrap your application with the PostHog provider. First, create a PostHogProvider.tsx
file in your project and configure it as follows:
Note: Replace YOUR_POSTHOG_API_KEY
with your actual PostHog API key.
In this setup:
- The
posthog.init
function is called in useEffect to initialize the PostHog client in production environments only. - The
PHProvider
wraps the entire app so that you can use PostHog's features anywhere in your component tree.
Step 3: Wrap Your Application with PostHog Provider
Now, modify your app/layout.tsx
to include the PostHog provider you just created:
For more advanced tracking, you can refer to the PostHog Next.js library documentation.