From a646c3f26b9a415af4cb1f6f8696e3c4fdc42661 Mon Sep 17 00:00:00 2001 From: Steven Tey Date: Mon, 30 Sep 2024 18:29:48 -0700 Subject: [PATCH] add support for apiKey --- packages/script/src/index.js | 12 +++++++++++- packages/web/src/generic.ts | 4 ++++ packages/web/src/types.ts | 6 ++++++ 3 files changed, 21 insertions(+), 1 deletion(-) diff --git a/packages/script/src/index.js b/packages/script/src/index.js index ec57037..390fca7 100644 --- a/packages/script/src/index.js +++ b/packages/script/src/index.js @@ -36,12 +36,14 @@ } const ah = script.getAttribute('data-api-host'); + const ak = script.getAttribute('data-api-key'); const am = script.getAttribute('data-attribution-model'); const co = script.getAttribute('data-cookie-options'); const qp = script.getAttribute('data-query-param'); return { apiHost: ah || 'https://api.dub.co', + apiKey: ak, attributionModel: am || 'last-click', cookieOptions: co ? JSON.parse(co) : null, queryParam: qp || 'ref', @@ -100,7 +102,7 @@ // Function to check for { keys } in the URL and update cookie if necessary function watchForQueryParams() { const searchParams = new URLSearchParams(window.location.search); - const { apiHost, cookieOptions, attributionModel, queryParam } = + const { apiHost, apiKey, cookieOptions, attributionModel, queryParam } = getOptions(script); let clickId = searchParams.get(CLICK_ID) || searchParams.get(OLD_CLICK_ID); @@ -109,9 +111,17 @@ const identifier = searchParams.get(queryParam); if (identifier) { + if (!apiKey) { + console.error( + '[Dub Analytics] Publishable API key not specified, which is required for tracking clicks. Please set the `apiKey` option.', + ); + return; + } + fetch(`${apiHost}/track/click`, { method: 'POST', headers: { + Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ diff --git a/packages/web/src/generic.ts b/packages/web/src/generic.ts index 227ce28..1359925 100644 --- a/packages/web/src/generic.ts +++ b/packages/web/src/generic.ts @@ -23,6 +23,10 @@ function inject(props: AnalyticsProps): void { script.setAttribute('data-api-host', props.apiHost); } + if (props.apiKey) { + script.setAttribute('data-api-key', props.apiKey); + } + if (props.attributionModel) { script.setAttribute('data-attribution-model', props.attributionModel); } diff --git a/packages/web/src/types.ts b/packages/web/src/types.ts index 3b75015..b4bba39 100644 --- a/packages/web/src/types.ts +++ b/packages/web/src/types.ts @@ -7,6 +7,12 @@ export interface AnalyticsProps { */ apiHost?: string; + /** + * The publishable API key to use for tracking click events. + * @example 'dub_publishable_xxxxxxxxxx' + */ + apiKey?: string; + /** * The Attribution Model to use for the analytics event. *