Skip to content

Commit 24afa50

Browse files
committed
fix query string API not respecting source middleware
1 parent 00a736f commit 24afa50

File tree

2 files changed

+29
-9
lines changed

2 files changed

+29
-9
lines changed

.changeset/few-starfishes-bake.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@segment/analytics-next': patch
3+
---
4+
5+
Fix query string API not respecting source middleware

packages/browser/src/browser/index.ts

Lines changed: 24 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -216,6 +216,24 @@ async function flushFinalBuffer(
216216
flushAnalyticsCallsInNewTask(analytics, buffer)
217217
}
218218

219+
const getQueryString = (): string => {
220+
// this is legacy code, I've just moved this into a function
221+
const hash = window.location.hash ?? ''
222+
const search = window.location.search ?? ''
223+
const term = search.length ? search : hash.replace(/(?=#).*(?=\?)/, '')
224+
return term
225+
}
226+
227+
const flushQueryString = async (
228+
analytics: Analytics,
229+
queryString: string
230+
): Promise<void> => {
231+
if (queryString.includes('ajs_')) {
232+
// not exactly sure why this async is in here or why we would need to await it, but it was legacy
233+
await analytics.queryString(queryString).catch(console.error)
234+
}
235+
}
236+
219237
async function registerPlugins(
220238
writeKey: string,
221239
cdnSettings: CDNSettings,
@@ -360,6 +378,9 @@ async function loadAnalytics(
360378
preInitBuffer.add(new PreInitMethodCall('page', []))
361379
}
362380

381+
// also, read the query string before we start loading the settings in case the URL changes
382+
const queryString = getQueryString()
383+
363384
const cdnURL = settings.cdnURL ?? getCDN()
364385
let cdnSettings =
365386
settings.cdnSettings ?? (await loadCDNSettings(settings.writeKey, cdnURL))
@@ -412,20 +433,14 @@ async function loadAnalytics(
412433
preInitBuffer
413434
)
414435

415-
const search = window.location.search ?? ''
416-
const hash = window.location.hash ?? ''
417-
418-
const term = search.length ? search : hash.replace(/(?=#).*(?=\?)/, '')
419-
420-
if (term.includes('ajs_')) {
421-
await analytics.queryString(term).catch(console.error)
422-
}
423-
424436
analytics.initialized = true
425437
analytics.emit('initialize', settings, options)
426438

427439
await flushFinalBuffer(analytics, preInitBuffer)
428440

441+
// not sure why we need to await this, but it was legacy -- can probably be removed
442+
await flushQueryString(analytics, queryString)
443+
429444
return [analytics, ctx]
430445
}
431446

0 commit comments

Comments
 (0)