@dreamdata/analytics-next
v2.0.4
Published
Analytics Next (aka Analytics 2.0) is the latest version of Dreamdata's JavaScript SDK.
Downloads
754
Readme
@dreamdata/analytics-next
Analytics Next (aka Analytics 2.0) is the latest version of Dreamdata's JavaScript SDK.
Quickstart
The easiest and quickest way to get started with Analytics 2.0 is to use it through Dreamdata. Alternatively, you can install it through NPM and do the instrumentation yourself.
Using with Dreamdata
Navigate to Dreamdata and choose JavaScript v2.0. Click "Reconfigure script" to go through a wizard on how to set up the script.
Using as an npm
package
- Install the package
# npm
npm install @dreamdata/analytics-next
# yarn
yarn add @dreamdata/analytics-next
# pnpm
pnpm add @dreamdata/analytics-next
- Import the package into your project and you're good to go (with working types)!
import { AnalyticsBrowser } from '@dreamdata/analytics-next'
const analytics = AnalyticsBrowser.load({ writeKey: '<YOUR_WRITE_KEY>' })
analytics.identify('hello world')
document.body?.addEventListener('click', () => {
analytics.track('document body clicked!')
})
Note that you can find your write key on the sources pages in the Dreamdata app.
Lazy / Delayed Loading
You can load a buffered version of analytics that requires .load
to be
explicitly called before initiating any network activity. This can be useful if
you want to wait for a user to consent before sending any tracking data.
- ⚠️ ️
.load
should only be called once.
export const analytics = new AnalyticsBrowser()
analytics.identify('hello world')
if (userConsentsToBeingTracked) {
analytics.load({ writeKey: '<YOUR_WRITE_KEY>' }) // destinations loaded, enqueued events are flushed
}
This strategy also comes in handy if you have some settings that are fetched asynchronously.
const analytics = new AnalyticsBrowser()
fetchWriteKey().then((writeKey) => analytics.load({ writeKey }))
analytics.identify('hello world')
Usage in Common Frameworks and SPAs
See or documentation on integrating with SPAs here.
FAQ
Adding Typescript support when using script tag
Install npm package
@dreamdata/analytics-next
as a dev dependency.Create
./typings/analytics.d.ts
// ./typings/analytics.d.ts
import type { AnalyticsSnippet } from '@dreamdata/analytics-next'
declare global {
interface Window {
analytics: AnalyticsSnippet
}
}
- Configure typescript to read from the custom
./typings
folder
// tsconfig.json
{
...
"compilerOptions": {
....
"typeRoots": [
"./node_modules/@types",
"./typings"
]
}
....
}
Handling initialization errors
Initialization errors get logged by default, but if you also want to catch these errors, you can do the following:
export const analytics = new AnalyticsBrowser();
analytics
.load({ writeKey: "MY_WRITE_KEY" })
.catch((err) => ...);