Skip to content

Commit

Permalink
add support for apiKey
Browse files Browse the repository at this point in the history
  • Loading branch information
steven-tey committed Oct 1, 2024
1 parent 3807811 commit a646c3f
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 1 deletion.
12 changes: 11 additions & 1 deletion packages/script/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down Expand Up @@ -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);
Expand All @@ -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({
Expand Down
4 changes: 4 additions & 0 deletions packages/web/src/generic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down
6 changes: 6 additions & 0 deletions packages/web/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down

0 comments on commit a646c3f

Please sign in to comment.