@softure-ai/analytics
v0.3.6
Published
SOFTURE AI analytics module: a cookieless acquisition channel tag carried through first-party URLs, and a funnel counter that keeps only daily sums per day, channel and step, fed by a beacon, a pixel and server hooks, with a report function.
Readme
@softure-ai/analytics
Depends on: core, db, security (its body reader).
Knows which acquisition channel a visitor came from (?z=newsletter) without a cookie and
without storing anything: the tag lives only in first-party URLs. A piece for the app's
proxy.ts keeps it on the address bar from page to page and through redirects, so a sign-up
posted from a tagged page knows its channel and auth's onRegistered hook can attribute the new
account. Extracted from an adopting app's channel tag and the channel part of its proxy, with the
parameter, its pattern and its length moved into configuration and the redirects split out of the
auth guard.
It also counts a funnel without personal data: how many visits reached each configured step from each channel on each day, and nothing else (no address, cookie, visit id or account). Extracted from an adopting app's funnel steps, beacon, counter table, endpoint and report query, with the steps, the cap and the time zone moved into configuration and the report turned into a function.
1. What it provides
- A configurable tag.
analytics({ channel: { param, pattern, maxLength } }): the query parameter (defaultz), what a valid value looks like (default lowercase words joined by-or_) and its longest length (default 32, at most 64). An invalid value is ignored, never trimmed, cut or repaired, unlesschannel.normalize: "trim-lowercase"trims and lowercases it first. - Renaming the parameter without losing shared links (
channel.legacyParams): earlier names are read afterparamand never written, and the tagger and the keeper move them toparamin the address bar (see "Renaming the channel parameter" below). - More than one first-party origin (
analytics({ origins })): an app serving public pages on the apex and the product onappOriginlists the apex; every check below accepts pages on any of them, and behind a reverse proxy the origin a request was sent to is read fromHost(readPublicOrigin,/server), never trusted beyond the configured list. - Propagation without a cookie (
/proxy,createChannelTagger(config, options?)):tag(request): a GET navigation (a browser page load, or a Next.js client navigation) without the parameter, coming from a first-party page with a valid one (Referer), is answered with a 307 to the same URL plus the tag, on the origin the request was sent to (a configured one, or the request URL's own host whenHostnames it, as on a dev server; elseappOrigin). Fetches, images, beacons and server actions pass untouched. What counts as a navigation is exported asisNavigation(request)(§4).carry(request, response): a first-party redirect another proxy piece answered with (auth's guard sending/account?z=adsto login) gets the request's channel added to itsLocation; a relativeLocationstays relative.options.channelFromReferer: a navigation from a first-party page without the parameter is tagged with the channel the page's URL implies (an article page →blog).options.targets: the navigationstagmay redirect, as pathnames (["/register"]) or a predicate({ target, source }) => boolean; every other path passes, so no extra 307 (or prefetch redirect) on pages the product leaves untagged.
- The tag on client navigations (
/next/channel-keeper,<ChannelKeeper />in the root layout): the proxy cannot recognise every Next.js client navigation (Next strips its router headers before the proxy runs, and a route served from the router's cache sends no request), so a small client component remembers the last valid tag seen in the address bar and puts it back withhistory.replaceStatewhen a navigation (next/link,router.push, a server action's redirect, areplaceStatefrom the page) lands without the parameter. It runs before the page's own effects, so a beacon already sends the tagged page. Withorigins, it also adds the tag to a link to another first-party origin when it is clicked (the browser's default referrer policy drops the query from a cross-originReferer, so the server alone cannot carry it across). It stores nothing;createChannelKeeper(rule)(/client, withtagLink) is its logic andgetChannelRule(config)(/server) its options as plain values. - The channel for the app (
/next):getChannel()in server actions, route handlers and hooks (read from the page the request was sent from),getChannelFromSearchParams()in pages. - Attribution of sign-ups:
attributeRegistration(onChannel)is anonRegisteredhook for auth that callsonChannel({ userId, channel }, ctx)inside the account's transaction when the sign-up came with a channel. Where the attribution goes (a column, a counter) is the app's choice. - Redirects that keep the tag (
/next):tagRedirect(path)adds the request's channel to a server action's redirect path (or a page's, from its own search params); auth takes it asrewriteRedirect, so its login, sign-up, reset and logout redirects, its login and register pages' redirect of a signed-in visitor andrequireUser's redirect to login land on a tagged URL. - Framework-free reading (
/server):parseChannel,readChannel(config, { url, referer, host }),withChannel,tagPath,hasChannelParam,isFirstParty,getFirstPartyOrigins,readPublicOrigin. - The funnel (
analytics({ funnel: { steps } })):analytics.funnel_countsholds one counter per (day, channel, step). Each step is counted one way:pixel:<FunnelPixel step="landing" />(/next) renders a 1×1 image (positioned absolutely unless it gets aclassName, decoded asynchronously); a page view counts without JavaScript. The step'spagesnames the pages it sits on, so a pixel requested from another page counts nothing (see "A pixel counted from the wrong page" below);beacon:<FunnelBeacon step="pricing" />(/next) orcreateFunnelReporter(endpoint)(/client) sendsnavigator.sendBeaconwithstep=<id>and nothing else, once per step;server: only the app's code counts it, withrecordFunnelStep(ctx, { step, channel })(/server),countRegistration("signup")(/next, an authonRegisteredhook) orcountFunnelStep("waitlist")(/next, any module's hook, e.g. the waitlist'sonJoined). The public endpoint refuses these steps, so nobody outside can inflate them.
- The endpoint (
/next,createFunnelRoute()):POSTtakes beacons (body at most 256 bytes),GETserves the pixel. Both count only requests sent from one of the app's pages (Referer,Sec-Fetch-Site), take the channel from that page (unlessfunnel.wire.channelFieldlets the request carry it) and answer the same (204, or the GIF) whatever the input; 503 only when the database fails. Every answer isno-store. - A wire format an existing app keeps (
funnel.wire): the step may come under several field names (stepFields: ["step", "k"]; the package's own beacon and pixel send the first), so pages cached with an older format keep counting while new ones send the new one;channelFieldreads the channel from the body or query too. - A channel from the page's path (
funnel.channelFromReferer): a step sent from a page without a tag can count under a channel derived from that page, e.g. every article view underblog. - The day is the calendar day in
timezoneofsofture.config.ts, whatever the server's zone. - A cap on new channels: at most
channelCap(default 100) distinct channels a day get their own counter; new ones past it count underOVERFLOW_CHANNEL(~overflow, which no channel pattern may accept). A channel counted before, today or on an earlier day, is never capped, nor onefunnel.isKnownChannel(channel, ctx)reports as known from the app's own tables. - The report (
/server):getFunnelReport(ctx, { days })returns the lastdaysdays (default 30) per channel (tagged,untaggedoroverflow), each step's count in funnel order, the busiest channel first, with totals.getFunnelDays(ctx, { days })returns the same window one day at a time (every channel summed, oldest first, a day with no visits as zeros), andformatFunnelDays(report)prints it as a plain-text table for a script or a job summary.pruneFunnelCounts(ctx, { keepDays })deletes older days.
2. Installation
npm install @softure-ai/analytics @softure-ai/core @softure-ai/db @softure-ai/security drizzle-orm zodPeer dependencies: next 16 and react 19 (for /next and /ui; /proxy, /server and
/client use Web APIs only) and drizzle-orm. The module depends on no other module in
softure.config.ts; it uses @softure-ai/security's body reader as a library, so it needs no
rate limit bucket.
3. Configuration
import { analytics } from "@softure-ai/analytics";
// in defineSoftureConfig({ modules: [...] }); every key is optional:
analytics({
origins: [], // e.g. ["https://example.com"] when the product runs on https://app.example.com
channel: { param: "z", legacyParams: [], pattern: /^[a-z0-9]+(?:[-_][a-z0-9]+)*$/, maxLength: 32, normalize: "none" },
funnel: {
steps: [
{ id: "landing", via: "pixel", pages: ["/"] }, // or (page) => page.pathname === "/"
{ id: "pricing" }, // via: "beacon" by default
{ id: "signup", via: "server" },
],
channelCap: 100,
wire: { stepFields: ["step"], channelField: null },
// channelFromReferer: (page) => (page.pathname.startsWith("/blog/") ? "blog" : null),
// isKnownChannel: (channel, ctx) => hasSignupsFrom(ctx.db, channel),
},
routes: { funnel: "/api/analytics/funnel" },
}),| Option | Default | Rule |
| --- | --- | --- |
| origins | [] | up to 16 http(s) origins besides appOrigin and the config's origins.trustedOrigins (no path, query or credentials), reduced to their origin; prefer the config's block, which every module reads |
| channel.param | "z" | lowercase letters, digits, - or _, starting with a letter, at most 32 characters |
| channel.legacyParams | [] | up to 4 earlier names of the parameter (the param rule), each once and none equal to param; every reader takes param first, then each of them in order (the first name present decides, valid or not); the package writes param only |
| channel.pattern | DEFAULT_CHANNEL_PATTERN | a RegExp without the g or y flag (they keep state between tests) |
| channel.maxLength | 32 | an integer from 1 to MAX_CHANNEL_LENGTH (64) |
| channel.normalize | "none" | "none" takes a value as it is; "trim-lowercase" trims and lowercases it before the pattern and length checks, on the server, in the browser keeper and in recordFunnelStep |
| funnel.steps | [] | up to 32 steps, ids kebab-case and at most 32 characters, each listed once; via is beacon (default), pixel or server |
| funnel.steps[].pages | none (any first-party page) | only on a pixel step: 1 to 32 pathnames (starting with a single /, no query or fragment; percent-encoded like the browser's, so /café matches), compared exactly with the pathname of the page the pixel was requested from, as the browser sends it (/ is only the root; a trailing slash or a basePath is part of it; the origin is not compared), or (page: URL) => boolean for dynamic routes or to tell origins apart; a pixel from any other page answers the same GIF and counts nothing; a throw is logged and counts nothing |
| funnel.channelCap | 100 | an integer from 1 to 10 000 |
| funnel.wire.stepFields | ["step"] | 1 to 4 field names (the param rule), each once; the endpoint takes the step from any of them (one value in all, or none counts); the package's beacon and pixel send the first (getFunnelStepField) |
| funnel.wire.channelField | null | a field name that is not a step field, or a list of 1 to 4 of them, each once: a valid channel in the body or query wins over the page's; an invalid one, or two values across the fields, is ignored |
| funnel.channelFromReferer | none | (page: URL) => string \| null, called for a counted step whose page has no tag; the answer passes the channel rule; a throw is logged and counts no channel |
| funnel.isKnownChannel | none | (channel, ctx) => boolean \| Promise<boolean>, asked for every count with a channel (keep it to one indexed lookup; ctx.db runs in the counting transaction); true keeps the channel's own counter past the cap; a throw fails the count like a database error |
| routes.funnel | /api/analytics/funnel | the endpoint's path; <FunnelPixel> and <FunnelBeacon> use it |
Renaming the channel parameter
Links shared with ?z=reddit stay in posts, comments and bookmarks for months. To move to ?ref= without
losing them, list the old name as a legacy one:
analytics({
channel: { param: "ref", legacyParams: ["z"] },
// only when pages send the channel in the beacon body themselves: cached pages keep sending `z`
funnel: { wire: { channelField: ["ref", "z"] } },
}),?z=redditand?ref=redditboth readredditon the server (readChannel,getChannel), in a page's search params (getChannelFromSearchParams), in the browser keeper and in the funnel endpoint;?ref=wins when both are present.- Links and redirects the package writes (
withChannel,tagPath,tagRedirect, the tagger, the keeper) carryrefonly. A navigation through?z=redditends with?ref=redditin the address bar: the tagger answers it with a 307 (withintargets), and the keeper rewrites it withreplaceStateafter client navigations. An invalid value under the old name is left as it is. - Drop the legacy name once old links no longer matter; without
legacyParamsnothing changes.
Counting sign-ups as the last step, next to the other hooks (countRegistration runs in a
savepoint and logs a failure instead of throwing, so a broken counter never refuses a sign-up):
import { countRegistration } from "@softure-ai/analytics/next";
const countSignup = countRegistration("signup");
auth({ onRegistered: async (event, ctx) => { await recordConsent(event, ctx); await countSignup(event, ctx); } }),Waitlist sign-ups count the same way through the waitlist's onJoined hook:
waitlist({ onJoined: countFunnelStep("waitlist") }). With double opt-in the sign-up counts on the
confirmation page, so the mailed link must carry the channel (rewriteConfirmationLink, waitlist
README §10).
Attribution in auth, next to another hook (privacy's consent):
import { attributeRegistration } from "@softure-ai/analytics/next";
import { recordRegistrationConsent } from "@softure-ai/privacy/server";
const recordConsent = recordRegistrationConsent();
const attributeChannel = attributeRegistration(({ userId, channel }, ctx) => saveSignupChannel(ctx.db, userId, channel));
auth({ onRegistered: async (event, ctx) => { await recordConsent(event, ctx); await attributeChannel(event, ctx); } }),Auth's redirects keep the tag: Next renders an action's redirect target (and a browser without
JavaScript follows its 303) from the URL the action passes to redirect(), which the proxy never
sees as a navigation. tagRedirect adds the channel of the page the action was posted from:
import { tagRedirect } from "@softure-ai/analytics/next";
auth({ rewriteRedirect: tagRedirect }),The app's own actions use it the same way: redirect(await tagRedirect("/thanks")). A path that
already carries the parameter is left as it is. A page that redirects while it renders passes its
own searchParams (its render's Referer is the page before): redirect(await tagRedirect("/", {
config, searchParams })); auth's login and register pages do this for a signed-in visitor through
the same rewriteRedirect option, and so does requireUser({ next, searchParams }) for a visitor
without a session (billing's payment page passes its parameters).
/next imports next/headers only when a function runs, so softure.config.ts (which
softure migrate loads in plain Node) can import it.
4. Mounting
The proxy piece, after the auth guard (the guard decides first; the tag never opens a private page):
// proxy.ts
import { createChannelTagger } from "@softure-ai/analytics/proxy";
import { createAuthGuard } from "@softure-ai/auth/proxy";
import { NextResponse, type NextRequest } from "next/server";
import softureConfig from "./softure.config";
const guard = createAuthGuard(softureConfig, { protect: ["/account"] });
const channels = createChannelTagger(softureConfig);
export function proxy(request: NextRequest): Response {
return channels.carry(request, guard(request)) ?? channels.tag(request) ?? NextResponse.next();
}The keeper, once in the root layout (inside <body>; it renders nothing and wraps itself in
<Suspense>). It has its own entry point because its client part imports next/navigation, which
plain Node (and so softure migrate loading softure.config.ts) cannot load from /next:
// app/layout.tsx
import { ChannelKeeper } from "@softure-ai/analytics/next/channel-keeper";
<body>
<ChannelKeeper />
{children}
</body>createChannelTagger throws at startup when analytics() is not in the configuration. To tag
navigations from untagged article pages, pass the same function the funnel uses:
createChannelTagger(softureConfig, { channelFromReferer: fromArticle }).
Only some paths. By default tag redirects a navigation to any path. Each one is a 307,
<Link> prefetches included, so an app that wants the tag only where it is read (sign-up, a
calculator) names those paths:
const channels = createChannelTagger(softureConfig, { targets: ["/register", "/calculator"] });
// or decide on the target and the page the visitor came from:
const channels = createChannelTagger(softureConfig, {
targets: ({ target, source }) => target.pathname === "/register" || source.pathname.startsWith("/blog/"),
});A list holds absolute pathnames compared exactly with the target's pathname (/register/ and
/register/step are other paths; a bad entry throws at startup). A predicate gets copies of both
URLs; only true tags, and a throw is logged and tags nothing. targets scopes tag only: carry
adds no request (it rewrites a redirect another piece already answered with), and
<ChannelKeeper /> still keeps the tag in the address bar of any page it sees one on.
What tag treats as a navigation. isNavigation(request) (exported from /proxy) is true for a
GET or HEAD with one of: Sec-Fetch-Mode: navigate (a browser page load), RSC: 1, or Next-Url
with no Sec-Fetch-Dest or Sec-Fetch-Dest: empty (a Next.js client navigation or prefetch). A bare
new NextRequest(url) has none of them, so a test of an app's proxy adds one
(headers: { "sec-fetch-mode": "navigate", referer: "https://app.example.com/?z=ads" }). A proxy in
front that strips Sec-Fetch-* and Next's headers makes tag pass every request (§12).
Redirect host without a proxy. On a dev server or a test stack (http://localhost:3100, neither
appOrigin nor in origins) Host equals the request URL's host, and tag redirects there (scheme
from X-Forwarded-Proto when present). Behind a proxy whose Host is not configured, it still
redirects to appOrigin.
Two origins behind a proxy. With public pages on https://example.com and the product on
appOrigin https://app.example.com, both served by one app behind a reverse proxy:
analytics({ origins: ["https://example.com"] }). The proxy in front must keep the Host header
(and should send X-Forwarded-Proto): the server's request.url names its own host and port, so the
package reads the public origin from Host and accepts it only when it is configured. A beacon or
pixel from either origin counts, tag keeps the visitor on the origin they asked for, and
<ChannelKeeper /> tags links that cross to the other origin. An app without the keeper (or without
JavaScript) carries the tag across only when the linking pages send a full cross-origin Referer
(Referrer-Policy: no-referrer-when-downgrade or looser). Keep the
proxy's matcher on pages (static files excluded); API routes the matcher reaches are not
navigations, so tag passes them.
The funnel endpoint, one line (the endpoint must be public: keep it out of the auth guard):
// app/api/analytics/funnel/route.ts
import { createFunnelRoute } from "@softure-ai/analytics/next";
export const { GET, POST } = createFunnelRoute();createFunnelRoute({ getContext }) counts in the context the app hands in instead of the registered
config's database, e.g. a test database: createFunnelRoute({ getContext: () => Promise.resolve(testCtx) }).
Steps on pages, in server components:
import { FunnelBeacon, FunnelPixel } from "@softure-ai/analytics/next";
<FunnelPixel step="landing" /> // on the landing page
<FunnelBeacon step="pricing" /> // on the pricing pageA pixel counted from the wrong page. A framework that prefetches links (Next's <Link> in a
production build) can load the linked page's pixel while another page is open, with that page as
the Referer: without pages, every page linking to / then counts landing under its own
channel. Give each pixel step its pages (pages: ["/"], or a predicate such as
(page) => page.pathname.startsWith("/blog/")) and those requests answer the GIF and count nothing.
Both throw on render for a step that is not configured with their kind. <FunnelPixel
className="…" /> hands the image the app's class instead of the default position: absolute. A client component that
counts wizard steps itself uses createFunnelReporter(endpoint) from /client.
A report, for an admin page or a script:
import { getFunnelReport } from "@softure-ai/analytics/server";
import { getAnalyticsContext } from "@softure-ai/analytics/next";
const report = await getFunnelReport(await getAnalyticsContext(), { days: 30 });5. Migrations and tables
Schema analytics, migration 0001_create_funnel_counts: funnel_counts (day, channel, step,
count), primary key (day, channel, step); channel is '' without a tag. The table checks the
step's shape, the channel's length and a positive count. The module's health check
(checkFunnelTable) answers once the table exists. Old days stay until the app prunes them
(pruneFunnelCounts); they hold no personal data.
With @softure-ai/jobs. @softure-ai/analytics/jobs ships the handler and the schedule, so the worker runs the
cleanup instead of an app cron (analytics.prune-funnel-counts daily, keeping the last keepDays days, today included; jobs README, "Schedules"):
// softure.config.ts
jobs({ schedules: { ...createAnalyticsJobSchedules({ keepDays: 400 }) } }),
// src/jobs/handlers.ts (the worker's handlers)
export const handlers: JobHandlers = { ...analyticsJobHandlers /* , the app's own */ };@softure-ai/jobs is an optional peer: an app without it keeps calling the function from its own cron.
6. Environment variables
None.
7. Switches
None.
8. Appearance
Nothing visible: <FunnelPixel> is a transparent 1×1 image and <FunnelBeacon> renders nothing.
9. Copy
None: the pixel and the beacon show nothing, and the report is data the app renders with its own
copy. The en dictionary in src/messages/ is empty.
10. Hooks
attributeRegistration(onChannel)builds an authonRegisteredhook (§3).onChannelruns in the account's transaction with the hook's context; an error it throws rolls the account back.countFunnelStep(step)builds a hook for any module's server event (auth'sonRegistered, the waitlist'sonJoined) that counts it (with the request's channel or without one) as aserverstep, in a savepoint of the event's transaction; it never throws. For waitlist sign-ups with double opt-in, the confirmation link must carry the channel: waitlist README §10.countRegistration(step)iscountFunnelStep(step)typed for auth'sonRegistered.tagRedirect(path, ctx?)fits auth'srewriteRedirectoption (§3) and the waitlist'srewriteConfirmationLink; auth (and the waitlist) keep their own path if it throws. Withctx.searchParams(a page's own redirect) it reads the channel from them alone.funnel.channelFromReferer(page)(§3) derives a channel from an untagged page's URL for the funnel;createChannelTagger(config, { channelFromReferer })(§4) does the same for navigations.funnel.isKnownChannel(channel, ctx)(§3) tells the cap which channels the app already knows.
Moving an existing funnel in. An app whose pages already send k=<step>&z=<channel> to its own
endpoint keeps its numbers with:
analytics({
channel: { param: "z", pattern: /^[a-z0-9-]+$/, maxLength: 20, normalize: "trim-lowercase" },
funnel: {
steps: [{ id: "landing", via: "pixel" }, { id: "article", via: "pixel" }, { id: "wizard-1" }],
wire: { stepFields: ["step", "k"], channelField: "z" },
channelFromReferer: (page) => (page.pathname.startsWith("/blog/") ? "blog" : null),
},
routes: { funnel: "/calculator/count" }, // the path cached pages post to
}),11. GDPR
The module sets no cookie and stores no personal data: the funnel keeps only sums per day, channel
and step, which no person can be found in, so it exports and deletes nothing. A channel the app
saves per account (through attributeRegistration) is the app's data: its export and deletion
belong to the app's own privacy contributor.
12. Limitations
- The
Referercarries the chain. An app that sendsReferrer-Policy: no-referrer,originorstrict-origin(or a page with such a<meta name="referrer">) breaks it at that page;same-originand the browser default keep it. - First party only. A hop through an origin outside
appOriginandorigins(a payment provider, a mail link) loses the tag unless the app puts it on the return URL itself (withChannel). - Crossing between first-party origins needs the keeper or a looser referrer policy. The
browser default sends only the origin in a cross-origin
Referer;<ChannelKeeper />tags such links on click, a link opened another way (copied, dragged) goes untagged. - A client navigation the proxy misses renders untagged on the server. The proxy re-tags a
router request that carries
Next-Url; one without it (or served from the router's cache) is tagged by<ChannelKeeper />in the browser after it renders, so that page's own server render (getChannelFromSearchParams) reads no channel. Actions, beacons and later pages see it. Without<ChannelKeeper />(or without JavaScript) such navigations stay untagged. - The keeper puts a dropped tag back. A page that removes the parameter with
history.replaceStategets it back; only another valid tag (or an invalid value, which ends the chain) replaces it. tagneeds navigation headers. Behind a proxy that stripsSec-Fetch-Mode(and Next'sRSC/Next-Url) no request is a navigation andtagsilently passes everything; the keeper still tags in the browser. Check withisNavigation(§4).- Last tag wins. A URL with its own tag replaces the earlier one; there is no first-touch memory without storage.
getChannel()reads the page the request came from; a page's own render reads itssearchParamsinstead.- A page that calls
requireUser()without its search params sends a visitor without a session to login tagged from its render'sReferer, the page before: the channel the proxy would have tagged it with, but not the page's own tag when the two differ, and none on a direct visit. Such pages passsearchParams, or sit behind the proxy's auth guard, which keeps the tag on the pages it protects (carry). - The funnel is a noise filter, not a defence. Its endpoint checks that a request comes from one
of the app's pages, but those headers come from the client: a forged
Refererpasses. The counts open nothing and the cap bounds the table, so the endpoint has no per-address rate limit on purpose: one would store every visitor's address. - Counts are visits that reached a step, each step at most once per page view; a visitor who opens the page twice counts twice. There is no unique-visitor number without an identifier.
