# @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](#using-with-dreamdata). Alternatively, you can
[install it through NPM](#using-as-an-npm-package) and do the instrumentation
yourself.

## Using with Dreamdata

Navigate to [Dreamdata](https://app.dreamdata.io) 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

1. Install the package

```sh
# npm
npm install @dreamdata/analytics-next

# yarn
yarn add @dreamdata/analytics-next

# pnpm
pnpm add @dreamdata/analytics-next
```

2. Import the package into your project and you're good to go (with working
   types)!

```ts
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_.

```ts
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.

```ts
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](https://tracking.docs.dreamdata.io/client-side/how-to-track-spas).

## FAQ

### Adding Typescript support when using script tag

1. Install npm package `@dreamdata/analytics-next` as a dev dependency.

2. Create `./typings/analytics.d.ts`

```ts
// ./typings/analytics.d.ts
import type { AnalyticsSnippet } from '@dreamdata/analytics-next'

declare global {
  interface Window {
    analytics: AnalyticsSnippet
  }
}
```

3. Configure typescript to read from the custom `./typings` folder

```jsonc
// 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:

```ts
export const analytics = new AnalyticsBrowser();
analytics
  .load({ writeKey: "MY_WRITE_KEY" })
  .catch((err) => ...);
```
