Skip to content

Commit 446c0ca

Browse files
feat: per-event user override in analytics().sendEvent() (#43)
sendEvent now accepts an optional `user` (UserContext) that identifies the event explicitly, overriding callbacks.getUser for that event. This covers server events whose subject isn't the request's session user — e.g. an email recipient resolved from a tracking link — so they land as real identity (userId/traits) instead of plain props.
1 parent dbeb2be commit 446c0ca

2 files changed

Lines changed: 12 additions & 3 deletions

File tree

packages/core/src/server.tsx

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import type {
2525
NextlyticsResult,
2626
RequestContext,
2727
ServerEventContext,
28+
UserContext,
2829
} from "./types";
2930
import { logConfigWarnings, validateConfig, withDefaults } from "./config-helpers";
3031
import { createNextlyticsMiddleware } from "./middleware";
@@ -314,7 +315,7 @@ export function Nextlytics(userConfig: NextlyticsConfig): NextlyticsResult {
314315
return {
315316
sendEvent: async (
316317
eventName: string,
317-
opts?: { props?: Record<string, unknown> }
318+
opts?: { props?: Record<string, unknown>; user?: UserContext }
318319
): Promise<{ ok: boolean }> => {
319320
// In the App Router no-arg path a missing pageRenderId means middleware
320321
// never ran — keep that as a hard error. With an explicit `req` the
@@ -332,7 +333,9 @@ export function Nextlytics(userConfig: NextlyticsConfig): NextlyticsResult {
332333
collectedAt: new Date().toISOString(),
333334
anonymousUserId,
334335
serverContext,
335-
userContext,
336+
// An explicit per-event user (e.g. an email recipient resolved from a
337+
// link) overrides the request-derived one from callbacks.getUser.
338+
userContext: opts?.user ?? userContext,
336339
properties: { ...propsFromCallback, ...opts?.props },
337340
};
338341
// Await full delivery, not just dispatch kickoff. Unlike the middleware

packages/core/src/types.ts

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -255,7 +255,13 @@ export type NextlyticsServerSide = {
255255
/** Send custom event from a server component, server action, or API route */
256256
sendEvent: (
257257
eventName: string,
258-
opts?: { props?: Record<string, unknown> }
258+
opts?: {
259+
props?: Record<string, unknown>;
260+
/** Identify the event's user explicitly. Overrides callbacks.getUser for
261+
* this event — e.g. an email recipient resolved from a link, where the
262+
* request has no session to derive identity from. */
263+
user?: UserContext;
264+
}
259265
) => Promise<{ ok: boolean }>;
260266
};
261267

0 commit comments

Comments
 (0)