Evaluate flags at the edge (Next.js middleware, Cloudflare Workers, Vercel Edge)
Resolve the visitor and their flags on the edge, then hand them to the browser SDK as bootstrap so the first paint has no flag flicker.
Two packages do this, and both use only fetch, so they run in edge runtimes: @lucida-analytics/next (Next.js middleware and server components) and @lucida-analytics/edge (Cloudflare Workers, Vercel Edge, Deno, Fastly Compute). Both read or set the first-party cookie lc_distinct_id. The cookie is only written when consent allows it (consentMode: opt_in by default, which needs the cookie lc_consent=granted; opt_out; off).
Next.js middleware
// middleware.ts (Next 16: proxy.ts, same body, function named `proxy`)
import { NextResponse, type NextRequest } from "next/server";
import { lucidaMiddleware } from "@lucida-analytics/next";
export async function middleware(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 } }));
}lucidaMiddleware reads the lc_distinct_id cookie (or mints an id for this request), fetches the flags once, forwards both as request headers (always overwritten, never taken from the client) and apply() sets the cookie if consent allows. The flag fetch has a budget (timeoutMs, 800 ms by default); past it the page renders with no flags rather than waiting.
Then bootstrap the browser SDK from a server component. middleware: true tells getBootstrap to trust the forwarded headers; set it only when the middleware runs on every such page.
// app/layout.tsx
import { headers } from "next/headers";
import { getBootstrap } from "@lucida-analytics/next";
import { LucidaNextProvider } from "@lucida-analytics/next/client";
const opts = { apiKey: process.env.NEXT_PUBLIC_LUCIDA_KEY!, middleware: true };
export default async function Layout({ children }: { children: React.ReactNode }) {
const bootstrap = await getBootstrap(await headers(), opts);
return <LucidaNextProvider apiKey={opts.apiKey} bootstrap={bootstrap}>{children}</LucidaNextProvider>;
}Without middleware, getBootstrap reads the cookie and evaluates the flags itself. Other options: host (default https://capture.lucidace.com), evaluate (replace the remote call, for example with local evaluation via nodeEvaluator from @lucida-analytics/next/server on the Node runtime), trustProxy. The Pages Router uses withLucida and LucidaPagesProvider. For the Vercel Flags SDK there is @lucida-analytics/flags-sdk.
Next.js with Cookie Munch (full consent flow)
The browser SDK writes the cookies the edge helpers read, once the visitor has decided. The flow, with consentMode left at opt_in:
Before a decision no
lc_*cookie exists.lucidaMiddlewaremints an id for that one request only; the browser SDK stays idle.The visitor grants statistics in the Cookie Munch banner. The
cookieMunchConsentbridge (pass it asmodulestoLucidaNextProvider, see Cookie Munch consent) records the decision and writes first-party cookies with the same attributes aslc_distinct_id(Path=/, one year,SameSite=Lax):lc_consent=granted, and the browser's anonymous distinct id aslc_distinct_id. Every bridge (Cookie Munch, Cookiebot, OneTrust, Osano, TCF, Google Consent Mode, Usercentrics) writeslc_consent=granted|deniedon each decision, never before one.The next request carries
lc_consent=granted(and the id), solucidaMiddlewaretreats storage as allowed andapply()keepslc_distinct_idset.getBootstrapreturns that same distinct id, so server-rendered flags are evaluated for the person the browser reports as.A later decline writes
lc_consent=deniedand removeslc_distinct_id.
modules are functions, and a server component cannot pass functions to a client component. So the layout fetches the bootstrap and hands it to a small client component of yours:
// app/lucida-provider.tsx
"use client";
import { LucidaNextProvider } from "@lucida-analytics/next/client";
import { cookieMunchConsent } from "@lucida-analytics/browser/consent";
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} options={{ consent: { mode: "opt_in" } }} modules={[cookieMunchConsent]}>
{children}
</LucidaNextProvider>
);
}In app/layout.tsx render <Lucida bootstrap={await getBootstrap(await headers(), opts)}>{children}</Lucida>.
If you read consent from somewhere else (your own cookie, a header), give the middleware a callback instead; it wins over lc_consent when it returns a boolean:
const lc = await lucidaMiddleware(req, {
apiKey: process.env.NEXT_PUBLIC_LUCIDA_KEY!,
middleware: true,
consent: (r) => {
const v = r.cookies.get("cookiemunch_statistics")?.value; // your CMP's own cookie
return v === undefined ? undefined : v === "1"; // undefined = fall back to lc_consent
},
});Cloudflare Workers
import { createEdgeClient, optionsFromEnv, requestBootstrap, bootstrapScript } from "@lucida-analytics/edge";
export default {
async fetch(req: Request, env: Record<string, string>, ctx: ExecutionContext) {
// env: LUCIDA_API_KEY (required), LUCIDA_SECRET_KEY (enables local evaluation), LUCIDA_HOST
const lc = createEdgeClient(optionsFromEnv(env, { waitUntil: (p) => ctx.waitUntil(p) }));
const b = await requestBootstrap(lc, req.headers.get("cookie"));
const html = `<script>${bootstrapScript({ distinctId: b.distinctId, flags: b.flags })}</script>...`;
const res = new Response(html, { headers: { "content-type": "text/html" } });
if (b.setCookie) res.headers.append("set-cookie", b.setCookie);
return res;
},
};requestBootstrap returns { distinctId, flags, setCookie? }; setCookie is present only for a new visitor whose consent allows storing the id. bootstrapScript({ distinctId, flags }) is the inline script body that sets window.__LUCIDA_BOOTSTRAP__; initialise the browser SDK with it:
init("lc_pk_...", { bootstrap: window.__LUCIDA_BOOTSTRAP__ });With a secret key (LUCIDA_SECRET_KEY) flags evaluate locally on the edge from definitions cached for ttlMs (30 seconds by default). Without one, or for cohort filters, the client calls POST /v1/flags. Never ship the secret key to a browser. Failures return {} rather than throwing.
You can also decide a flag directly: await lc.isFeatureEnabled("new-checkout", distinctId), getFlag, getFlagPayload, getAllFlags. Send events with lc.capture(distinctId, "event", props); waitUntil finishes the send after the response, otherwise await lc.flush().
Vercel Edge
Use @lucida-analytics/edge the same way in an Edge route or middleware: read LUCIDA_API_KEY from process.env (optionsFromEnv(process.env)) and call requestBootstrap(lc, req.headers.get("cookie")). Pass { waitUntil } from the event your handler receives so captures complete after the response. In Next.js on Vercel, prefer lucidaMiddleware above.