Skip to main content
This guide covers both the App Router (Next.js 13+) and Pages Router (Next.js 12 and earlier).

Install the Package

npm
yarn
pnpm

App Router (Next.js 13+)

Create an Analytics Component

Grain Tag must be initialized on the client. Create a client component that runs once:

Add to Your Root Layout

Add Environment Variable

Create a .env.local file:
Replace your-tenant-id with the alias from your dashboard.

Use in Components

Now you can track events from any Client Component:
Server vs Client Components: track(), identify(), and other Grain Tag functions must be called from Client Components (with the 'use client' directive) or inside useEffect. Grain Tag is SSR safe — init() returns a no-op in non-browser environments — but tracking functions need the browser to work.
Automatic page views: Grain Tag hooks into the History API to track page views and navigation automatically. You do not need a page view tracker component — this works out of the box with Next.js App Router.

Identify Users


Pages Router (Next.js 12)

Initialize in _app.tsx

Add Environment Variable

Create a .env.local file:

Use in Pages

Automatic page views: Grain Tag automatically tracks navigation via the History API for both App Router and Pages Router. No manual page view tracking is needed.

Server-Side Tracking

For tracking events from API routes or Server Actions, use @grainql/analytics-web (a different package designed for server-side use):

API Routes

Serverless tip: Use { flush: true } to send events immediately before the function terminates.

Server Actions (App Router)


What’s Next?

Core API Reference

See all available methods and options

User Identification

Track users across sessions

Event Best Practices

Learn what to track and how to structure events

Server-Side Setup

Advanced server-side configuration
Vercel deployment: All environment variables starting with NEXT_PUBLIC_ are automatically available in the browser. Keep secret keys (for server-side tracking) private by omitting the NEXT_PUBLIC_ prefix.
Need remote configuration or feature flags? See @grainql/analytics-web for remote config, React hooks (useConfig, useTrack, GrainProvider), and more.