Skip to main content
This page installs Grain Tag in a Next.js app, with the App Router (Next.js 13 and later) or the Pages Router (Next.js 12 and earlier). Then it sends an event from a route handler with Analytics Web. Steps 1 to 5 use @grainql/tag. Step 6 uses @grainql/analytics-web.

Before you start

You need three things:
  • Your tenant alias. The dashboard at https://grainql.com/dashboard shows it. It is not the UUID.
  • A .env.local file. Next.js exposes every variable with the NEXT_PUBLIC_ prefix to the browser. A variable without the prefix stays on the server.
  • For step 6, a secret key from the dashboard, in the server-only variable GRAIN_SECRET_KEY. Read Authentication.

1. Install Grain Tag

2. Initialize in the App Router

Grain Tag runs in the browser. Create a Client Component that calls init one time.
Add the component to the root layout.
init returns a no-op stub outside a browser, so the import is safe in a server render. If you use the Pages Router, skip to step 3.

3. Initialize in the Pages Router

Call init in a useEffect in pages/_app.tsx.

4. Make sure that events arrive

Open the app in a browser. In the developer console, run:
The dashboard shows the installation_test event within 30 seconds. If the event does not appear, read Troubleshooting.

5. Track an event and identify a user

Call track and identify from a Client Component, or inside a useEffect. In the App Router, the component needs the 'use client' directive. Both routers navigate through the History API, so Grain Tag tracks each route change as a page view.
track and identify called before init are queued and replayed after initialization. For consent, call getInstance()?.consent.grant() from a Client Component. Read Track an event and Identify users.

6. Server-side events

Route handlers and Server Actions use Analytics Web, a different package, with the SERVER_SIDE strategy and the secret key.
The { flush: true } option sends the event before the function returns. Without it, a serverless function can stop before the batch timer fires, and the event is lost. A Server Action in app/actions.ts with the 'use server' directive uses the same client and the same track call.
Do not put the secret key in a NEXT_PUBLIC_ variable. Next.js sends every NEXT_PUBLIC_ variable to the browser.
Read Node.js and servers.

Next steps

Core methods

Every method of both SDKs, with signatures.

Identify users

Anonymous IDs, daily rotating IDs, and identify.

React hooks

Analytics Web, the provider, and remote configuration in React.

Configuration options

Every option of both SDKs, with defaults.