Simple Analytics for Next.js

Tracking Events

Using event tracking in Server Actions and Route Handlers

With Simple Analytics for Next.js you can collect events across your application, e.g. button clicks, or form submissions, using the trackEvent function.

Learn more about events in the Simple Analytics docs.

Tracking client-side events

The client-side trackEvent function requires the SimpleAnalytics component to be used to track events in client components.

page.tsx
"use client";
 
import { trackEvent } from "@simpleanalytics/next";
 
export default function Page() {
  function addToCart() {
    // ...
 
    trackEvent("added_to_cart");
  }
 
  return (
    <> 
      {/* ... */}
    </>
  )
}

Adding metadata to events

You can add additional metadata to events to provide more context about the event.

page.tsx
"use client";
 
import { trackEvent } from "@simpleanalytics/next";
 
export default function Page() {
  function purchase() {
    trackEvent("addToCart", {
      product_id: "123",
      currency: "EUR"
    });
  }
 
  return (
    <>
      {/* ... */}
    </>
  )
}

Tracking server-side events

You can also track events in Server Actions and Route Handlers. However, you must explicitly pass the request object or the request headers to the trackEvent function.

Usage in Server Actions

"use server";
 
import { after } from "next/server";
import { headers } from "next/headers";
import { trackEvent } from "@simpleanalytics/next/server";
 
export async function purchaseAction() {
  // ...
 
  after(async () => {
    await trackEvent("purchase", {
      headers: await headers(),
      // Pass metadata (optional)
      metadata: {
        product_id: "123",
        currency: "EUR"
      },
    });
  });
 
  return { success: true };
}

Usage with Route Handlers

import { after, NextRequest, NextResponse } from "next/server";
import { trackEvent } from "@simpleanalytics/next/server";
 
export async function POST(request: NextRequest) {
  // ...
 
  after(async () => {
    await trackEvent("purchase", {
      request,
      // Pass metadata (optional)
      metadata: {
        product_id: "123",
        currency: "EUR"
      },
    });
  });
 
  return NextResponse.json({ success: true });
}

On this page