Skip to content

Commit a646c3f

Browse files
committed
add support for apiKey
1 parent 3807811 commit a646c3f

File tree

3 files changed

+21
-1
lines changed

3 files changed

+21
-1
lines changed

packages/script/src/index.js

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,12 +36,14 @@
3636
}
3737

3838
const ah = script.getAttribute('data-api-host');
39+
const ak = script.getAttribute('data-api-key');
3940
const am = script.getAttribute('data-attribution-model');
4041
const co = script.getAttribute('data-cookie-options');
4142
const qp = script.getAttribute('data-query-param');
4243

4344
return {
4445
apiHost: ah || 'https://api.dub.co',
46+
apiKey: ak,
4547
attributionModel: am || 'last-click',
4648
cookieOptions: co ? JSON.parse(co) : null,
4749
queryParam: qp || 'ref',
@@ -100,7 +102,7 @@
100102
// Function to check for { keys } in the URL and update cookie if necessary
101103
function watchForQueryParams() {
102104
const searchParams = new URLSearchParams(window.location.search);
103-
const { apiHost, cookieOptions, attributionModel, queryParam } =
105+
const { apiHost, apiKey, cookieOptions, attributionModel, queryParam } =
104106
getOptions(script);
105107

106108
let clickId = searchParams.get(CLICK_ID) || searchParams.get(OLD_CLICK_ID);
@@ -109,9 +111,17 @@
109111
const identifier = searchParams.get(queryParam);
110112

111113
if (identifier) {
114+
if (!apiKey) {
115+
console.error(
116+
'[Dub Analytics] Publishable API key not specified, which is required for tracking clicks. Please set the `apiKey` option.',
117+
);
118+
return;
119+
}
120+
112121
fetch(`${apiHost}/track/click`, {
113122
method: 'POST',
114123
headers: {
124+
Authorization: `Bearer ${apiKey}`,
115125
'Content-Type': 'application/json',
116126
},
117127
body: JSON.stringify({

packages/web/src/generic.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,10 @@ function inject(props: AnalyticsProps): void {
2323
script.setAttribute('data-api-host', props.apiHost);
2424
}
2525

26+
if (props.apiKey) {
27+
script.setAttribute('data-api-key', props.apiKey);
28+
}
29+
2630
if (props.attributionModel) {
2731
script.setAttribute('data-attribution-model', props.attributionModel);
2832
}

packages/web/src/types.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,12 @@ export interface AnalyticsProps {
77
*/
88
apiHost?: string;
99

10+
/**
11+
* The publishable API key to use for tracking click events.
12+
* @example 'dub_publishable_xxxxxxxxxx'
13+
*/
14+
apiKey?: string;
15+
1016
/**
1117
* The Attribution Model to use for the analytics event.
1218
*

0 commit comments

Comments
 (0)