Skip to content

Commit 6890277

Browse files
committed
update script
1 parent bd81e10 commit 6890277

File tree

1 file changed

+38
-33
lines changed

1 file changed

+38
-33
lines changed

packages/script/src/index.js

Lines changed: 38 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -118,44 +118,49 @@
118118
const searchParams = new URLSearchParams(window.location.search);
119119
const { apiHost, apiKey, queryParam } = getOptions(script);
120120

121+
// When the clickId is present in the URL, set the cookie (?dub_id=...)
121122
let clickId = searchParams.get(CLICK_ID) || searchParams.get(OLD_CLICK_ID);
122123

123124
if (clickId) {
124125
checkCookieAndSet(clickId);
125-
} else {
126-
const identifier = searchParams.get(queryParam);
127-
128-
if (identifier) {
129-
if (!apiKey) {
130-
console.error(
131-
'[Dub Analytics] Publishable API key not specified, which is required for tracking clicks. Please set the `apiKey` option.',
132-
);
133-
return;
134-
}
135-
136-
fetch(`${apiHost}/track/click`, {
137-
method: 'POST',
138-
headers: {
139-
Authorization: `Bearer ${apiKey}`,
140-
'Content-Type': 'application/json',
141-
},
142-
body: JSON.stringify({
143-
identifier,
144-
}),
145-
}).then(async (res) => {
146-
if (!res.ok) {
147-
const { error } = await res.json();
148-
console.error(
149-
`[Dub Analytics] Failed to track click: ${error.message}`,
150-
);
151-
return;
152-
}
153-
154-
const { clickId } = await res.json(); // Response: { clickId: string }
155-
checkCookieAndSet(clickId);
156-
});
157-
}
126+
return;
127+
}
128+
129+
// When the identifier is present in the URL, track the click and set the cookie (?ref=...)
130+
const identifier = searchParams.get(queryParam);
131+
132+
if (!identifier) {
133+
return;
134+
}
135+
136+
if (!apiKey) {
137+
console.error(
138+
'[Dub Analytics] Publishable API key not specified, which is required for tracking clicks. Please set the `apiKey` option.',
139+
);
140+
return;
158141
}
142+
143+
fetch(`${apiHost}/track/click`, {
144+
method: 'POST',
145+
headers: {
146+
Authorization: `Bearer ${apiKey}`,
147+
'Content-Type': 'application/json',
148+
},
149+
body: JSON.stringify({
150+
identifier,
151+
}),
152+
}).then(async (res) => {
153+
if (!res.ok) {
154+
const { error } = await res.json();
155+
console.error(
156+
`[Dub Analytics] Failed to track click: ${error.message}`,
157+
);
158+
return;
159+
}
160+
161+
const { clickId } = await res.json(); // Response: { clickId: string }
162+
checkCookieAndSet(clickId);
163+
});
159164
}
160165

161166
watchForQueryParams();

0 commit comments

Comments
 (0)