Skip to content

Commit

Permalink
[web] Include flags in custom events
Browse files Browse the repository at this point in the history
  • Loading branch information
AndyBitz committed Apr 9, 2024
1 parent 5cfe56c commit 254f689
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 4 deletions.
6 changes: 4 additions & 2 deletions packages/web/src/generic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,8 @@ function inject(
*/
function track(
name: string,
properties?: Record<string, AllowedPropertyValues>
properties?: Record<string, AllowedPropertyValues>,
options?: { flags?: string[] }
): void {
if (!isBrowser()) {
const msg =
Expand All @@ -106,7 +107,7 @@ function track(
}

if (!properties) {
window.va?.('event', { name });
window.va?.('event', { name, options });
return;
}

Expand All @@ -118,6 +119,7 @@ function track(
window.va?.('event', {
name,
data: props,
options,
});
} catch (err) {
if (err instanceof Error && isDevelopment()) {
Expand Down
27 changes: 25 additions & 2 deletions packages/web/src/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,19 @@ interface ContextWithHeaders {

type Context = ContextWithRequest | ContextWithHeaders;

interface Options {
flags?: string[];
}

interface RequestContext {
get: () => {
headers: Record<string, string | undefined>;
url: string;
waitUntil?: (promise: Promise<unknown>) => void;
flags?: {
getValues: () => Record<string, unknown>;
reportValue: (key: string, value: unknown) => void;
};
};
}

Expand All @@ -33,7 +41,8 @@ const logPrefix = '[Vercel Web Analytics]';
export async function track(
eventName: string,
properties?: Record<string, AllowedPropertyValues>,
context?: Context
context?: Context,
options?: Options
): Promise<void> {
const ENDPOINT =
process.env.VERCEL_WEB_ANALYTICS_ENDPOINT || process.env.VERCEL_URL;
Expand Down Expand Up @@ -98,12 +107,26 @@ export async function track(

const url = new URL(origin);

let flagsToReport: Record<string, unknown> = {};
const allFlags = requestContext?.flags?.getValues();
if (options?.flags && allFlags) {
options.flags.forEach((key) => {
flagsToReport[key] = allFlags[key];
});
} else if (allFlags) {
// Default to all flags. The ingest endpoint will truncate them.
flagsToReport = allFlags;
}

const body = {
o: origin,
ts: new Date().getTime(),
r: '',
en: eventName,
ed: props,
flags: {
plain: flagsToReport,
},
};

const hasHeaders = Boolean(headers);
Expand Down Expand Up @@ -135,7 +158,7 @@ export async function track(
body: JSON.stringify(body),
method: 'POST',
})
// We want to always consume to body; some cloud providers track fetch concurrency
// We want to always consume the body; some cloud providers track fetch concurrency
// and may not release the connection until the body is consumed.
.then((response) => response.text())
.catch((err: unknown) => {
Expand Down

0 comments on commit 254f689

Please sign in to comment.