Install Lucida on Next.js

Add the Lucida browser SDK to a Next.js App Router app: packages, provider, first-party /ingest path, CSP, consent and a first-event check.

Embed
Preview of the card
<a href="https://lucidace.com/help/install-nextjs"><img src="https://lucidace.com/help/_api/public/orgs/af34862a-c837-4478-8335-0505efe40459/spaces/2f4b888b-c4e6-488b-81bd-6e838fb12d2e/pages/f67a02c0-2f36-4ce9-bafd-0052c52b9f62/social-card.svg?v=3e7ae33eec8b" alt="Install Lucida on Next.js" width="600" height="315"></a>

For the Next.js App Router. @lucida-analytics/next declares the peer ranges next >=14 and react >=18. Its tests do not run a real Next.js app, so those are peer ranges, not a tested matrix.

1. Install

npm install @lucida-analytics/next @lucida-analytics/browser @lucida-analytics/react

Put your public key in .env.local:

NEXT_PUBLIC_LUCIDA_KEY=lc_pk_YOUR_PUBLIC_KEY

Or run lucida init --framework next --host https://capture.lucidace.com: it prints these edits. --write creates proxy.ts (Next 16 or later) or middleware.ts (older), and next.config.mjs only if you have no next.config.*. It never overwrites a file.

Which key is read when

Variable

Key

Read at

Where it may appear

NEXT_PUBLIC_LUCIDA_KEY

project public key lc_pk_...

build time: Next inlines NEXT_PUBLIC_* into the bundle

the browser (safe to ship)

LUCIDA_SECRET_KEY

project secret key lc_sk_... (capture for server events)

run time, server only

never prefixed NEXT_PUBLIC_, never in the browser

LUCIDA_PRIVACY_KEY

project secret key with privacy:execute (minted with your account key)

run time, server only (or stored in Cookie Munch)

never in the browser

LUCIDA_ACCOUNT_KEY

account key lc_pat_...

your shell or CI only, to create projects and mint keys

never in the app

Set NEXT_PUBLIC_LUCIDA_KEY before next build. Supplied only at run time it is an empty string in the bundle and analytics silently does not load.

The one-line tag

If you only need consent-gated analytics (no flags bootstrap or route templates), skip the provider and drop in <LucidaTag /> from @lucida-analytics/react (0.1.5 or later: the bundle is marked "use client", so it imports straight into a server component such as app/layout.tsx, no wrapper file; also exported by @lucida-analytics/next/client):

// app/layout.tsx (a client component is fine anywhere in the tree)
import { LucidaTag } from "@lucida-analytics/next/client";
<LucidaTag uid={session?.user.id} />

It reads NEXT_PUBLIC_LUCIDA_KEY (or publicKey), and guarantees:

  • No key, nothing loads: it renders nothing and imports nothing.

  • It cannot break the page: the SDK is a dynamic import, module load and init never throw, and a failed load resolves to a no-op (no unhandled rejection).

  • One client: the init is memoised per key, so remounts and React StrictMode never init twice.

  • Consent first: consent.mode is opt_in and it follows Cookie Munch when Cookie Munch is on the page (cookieMunch={false} to turn that off).

  • referralParams: []: ?ref= belongs to your referral platform under its own consent category, so Lucida does not record it as analytics.

  • exposeGlobal: true: window.lucida, so a Watchtower browser client on the page links lucida.session_id. (Browser 0.1.15 also turns it on by itself when it detects a Watchtower browser SDK; exposeGlobal: false opts out.)

  • Server layouts: modules also takes names ("replay", "heatmaps", "forms", "guides", ...; or replay / heatmaps boolean props), loaded inside the client component, so a server layout needs no "use client" wrapper: <LucidaTag publicKey={process.env.NEXT_PUBLIC_LUCIDA_KEY} modules={["replay"]} identify={sub} />. Functions cannot cross the server/client boundary; strings can.

  • useFlag(key) reads a flag under LucidaTag alone (no provider), re-renders when flags load, and records one exposure after mount.

  • identify(uid) runs only after the client is ready, and again when uid changes. options and modules are merged over the defaults.

2. Init with the key

LucidaNextProvider comes from @lucida-analytics/next/client. Put it in a small "use client" file so you can pass modules:

// app/lucida-provider.tsx
"use client";
import { LucidaNextProvider } from "@lucida-analytics/next/client";
import type { Bootstrap } from "@lucida-analytics/next";

export function Lucida({ bootstrap, children }: { bootstrap: Bootstrap; children: React.ReactNode }) {
  return (
    <LucidaNextProvider apiKey={process.env.NEXT_PUBLIC_LUCIDA_KEY!} bootstrap={bootstrap}>
      {children}
    </LucidaNextProvider>
  );
}

To tie Lucida to your sign-in, pass the user id: <LucidaNextProvider ... identify={session?.user.id ?? null}> (optional identifyProps={{ plan: "pro" }}). It identifies when the id appears or changes and calls reset() when a signed-in user signs out, never on a first signed-out render.

// app/layout.tsx (server component)
import { headers } from "next/headers";
import { getBootstrap } from "@lucida-analytics/next";
import { Lucida } from "./lucida-provider";

const opts = { apiKey: process.env.NEXT_PUBLIC_LUCIDA_KEY!, middleware: true };

export default async function Layout({ children }: { children: React.ReactNode }) {
  return <html><body><Lucida bootstrap={await getBootstrap(await headers(), opts)}>{children}</Lucida></body></html>;
}

Host. The provider sends to /ingest on your own domain only when the rewrite in step 4 is set up with withLucidaRewrites() (it marks the build with NEXT_PUBLIC_LUCIDA_REWRITE). Without that marker it sends straight to https://capture.lucidace.com, so a missing rewrite never drops events silently. An explicit options={{ apiHost }} always wins. In development, the first 404 from a same-origin apiHost logs one console error: "rewrite missing: add withLucidaRewrites() to next.config or set apiHost".

Request helper (avoids flag flicker). Next 16 renamed middleware.ts to proxy.ts; the helper is the same:

// proxy.ts (Next 16). On Next 14 and 15 this is middleware.ts and the function is `middleware`.
import { NextResponse, type NextRequest } from "next/server";
import { lucidaMiddleware } from "@lucida-analytics/next";

export async function proxy(req: NextRequest) {
  const lc = await lucidaMiddleware(req, { apiKey: process.env.NEXT_PUBLIC_LUCIDA_KEY!, middleware: true });
  return lc.apply(NextResponse.next({ request: { headers: lc.requestHeaders } }));
}

Identify when auth resolves and reset on sign-out, in a client component (useLucida() is null during server rendering, so call it in an effect):

"use client";
import { useEffect } from "react";
import { useLucida } from "@lucida-analytics/next/client";

export function IdentifyUser({ user }: { user: { id: string; email: string } | null }) {
  const lucida = useLucida();
  useEffect(() => {
    if (user) lucida?.identify(user.id, { email: user.email });
  }, [lucida, user]);
  return null;
}
// sign-out handler: useLucida()?.reset();

3. Content Security Policy

With the /ingest path on your own domain, the browser only talks to your origin:

script-src  'self';
connect-src 'self';

If you send straight to the cloud instead, use connect-src 'self' https://capture.lucidace.com;. Next.js may need a nonce for its own inline scripts; pass the same nonce to the SDK with the nonce option. Guides, web experiments and the toolbar need more lines: see Content Security Policy.

4. Reverse proxy

@lucida-analytics/next ships the rule. In next.config.js:

const { withLucidaRewrites } = require("@lucida-analytics/next");
module.exports = withLucidaRewrites({ /* your Next config */ });

It adds the rewrite (before yours), skipTrailingSlashRedirect and the NEXT_PUBLIC_LUCIDA_REWRITE marker. If you write the rewrite by hand with lucidaRewrites(), also set NEXT_PUBLIC_LUCIDA_REWRITE=/ingest at build time (or pass apiHost: "/ingest"). It forwards only /v1/*, from /ingest. withLucidaRewrites(config, { path, host }) and lucidaRewrites({ path, host }) change either (for self-hosting, set host to your capture host). Details, and the same idea for Vercel, Cloudflare and nginx, are in Serve Lucida from your own domain.

The SDK default is opt_out: it stores and sends before the visitor decides (a project created on or after 2026-11-16 serves opt_in from its settings, which wins; <LucidaTag> is opt_in too). For prior consent, start in opt_in and use the Cookie Munch bridge as a module:

import { cookieMunchConsent } from "@lucida-analytics/browser/consent";
// <LucidaNextProvider ... options={{ consent: { mode: "opt_in" } }} modules={[cookieMunchConsent]}>

modules on the provider needs @lucida-analytics/next 0.1.5 (with @lucida-analytics/browser 0.1.8). Without Cookie Munch, call lucida.setConsent({ analytics: true, replay: true, marketing: false }) from your own banner. See Cookie Munch consent and Consent by location.

Identify visitors with Atlas

If you sign users in with Atlas, @lucida-analytics/browser/atlas (browser 0.1.15) follows the Atlas browser session for you. It needs Atlas JS 0.29 or later, which exposes window.Atlas.session and fires an atlas:session event (detail: { signedIn, userId }).

import { cookieMunchConsent } from "@lucida-analytics/browser/consent";
import { atlasIdentity } from "@lucida-analytics/browser/atlas";
// <LucidaNextProvider ... options={{ consent: { mode: "opt_in" } }}
//   modules={[cookieMunchConsent, atlasIdentity({ property: "atlas_user_id" })]}>
  • On sign-in it calls identify with the Atlas user id. If you pass property, that person property is also set to the id. It is optional.

  • On sign-out it calls reset, but only when this module did the identify. It never resets a visitor you identified yourself.

  • The Atlas global may load after Lucida. The module looks for it for about 10 seconds, then relies on the atlas:session event.

6. Check the first event

  • Terminal: lucida init --framework next --host https://capture.lucidace.com --project $LUCIDA_PROJECT_ID --verify waits for a new event to reach the project (needs an account key). Open your app and load a page.

  • App: the Install wizard (onboarding page) waits for the first event and tells you when it arrives.

If nothing arrives, look for Refused to connect in the console (CSP) and check that /ingest/v1/batch on your domain answers 2xx.

More

Edge flags, SDK pinning, quickstart (replay, groups, URL privacy), all frameworks.

Updated