Simple Analytics for Next.js

Tracking Pageviews

Using manual pageview tracking

The trackPageview function can be used to track pageviews manually. You might use manual page tracking to add additional metadata to the pageview, e.g. whether the user is signed in.

Disabling automatic pageview collection

The SimpleAnalytics component automatically collects pageviews, if we want to collect pageviews manually we should disable auto collection to prevent recording duplicate pageviews.

We can disable automatic pageview collection by setting the autoCollect property to false:

<SimpleAnalytics autoCollect={false} />

Tracking pageviews server-side

Simple Analytics determines the country of the visitor based on their time zone. Unlike during client-side tracking, this information is not available on when receiving a request on the server.

However, certain hosting provider, e.g. Vercel, Cloudflare, and Amazon CloudFront, might include the visitor's time zone (by default or optionally) in a request headers.

If one of the headers is present, the time zone will automatically be include with the information send to Simple Analytics unless explicitly ignored.

Usage in Edge Middleware

This feature is experimental

Tracking pageviews in middleware is an experimental feature and does not support the same functionality as the client-side tracking implementation.

You can add pageview tracing application-wide using trackPageview and Next.js Edge Middleware.

middleware.ts
import { NextRequest, NextFetchEvent, NextResponse } from "next/server";
import { trackPageview } from "@simpleanalytics/next/server";
 
export function middleware(request: NextRequest, event: NextFetchEvent) {
  event.waitUntil(trackPageview({ request }));
 
  return NextResponse.next();
}
 
export const config = {
  matcher: [
    /*
     * Match all request paths except for the ones starting with:
     * - api (API routes)
     * - _next/static (static files)
     * - _next/image (image optimization files)
     * - favicon.ico, apple-icon.(jpg|jpeg|png), icon.(ico|jpg|jpeg|png|svg), sitemap.xml, robots.txt (metadata files)
     */
    '/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt|apple-icon\.(?:jpg|jpeg|png)|icon\.(?:ico|jpg|jpeg|png|svg)).*)',
  ],
}

Usage in Server Components

You can track pageviews manually in React Server Components using trackPageview. Enabling more granular control per page while tracking visitors, including specifying page specific metadata.

Usage without request object

We use the request headers and must specify the path explicity because the request object is not accessible in Server Components.

The function headers() cannot be called inside the after callback when used in a Server Component.

app/blog/page.tsx
import { after } from "next/server";
import { headers } from "next/headers";
import { trackPageview } from "@simpleanalytics/next/server";
 
export default async function Page() {
  const headerList = await headers();
 
  after(async () => {
    await trackPageview("/blog", { headers: headerList });
  });
 
  return (
    <> 
      {/* ... */}
    </>
  )
}

Handling parameters in dynamic routes

For routes containing dynamic segments (e.g. app/blog/posts/[id]/page.tsx), you can include the segments and reconstruct the path before passing it to trackPageview.

app/blog/posts/[id]/page.tsx
import { after } from "next/server";
import { headers } from "next/headers";
import { trackPageview } from "@simpleanalytics/next/server";
 
interface PageProps {
  params: Promise<{ id: string }>;
}
 
export default async function Page({ params }: PageProps) {
  const headerList = await headers();
 
  const { id } = await params;
 
  after(async () => {
    await trackPageview(`/blog/posts/${id}`, { headers: headerList });
  });
 
  // ...
}

On this page