# Install Clicklore

Instructions for an AI coding agent working in an existing application. Inspect the app, choose one installation path below, integrate it, verify it, and report the result. Preserve existing providers, routing, configuration, styles and application behavior. Do not scaffold a new app.

## Inspect the app and obtain configuration

1. Read the repository's agent instructions, `package.json`, app entry points, router and bundler configuration. In a monorepo, identify the application workspace and install dependencies there, using the repository's workspace conventions.
2. Detect the package manager from the applicable lockfile. Check `packageManager` in `package.json` if multiple lockfiles exist; follow the repository's established manager. Do not create a second lockfile.

   | Lockfile | Package manager |
   | --- | --- |
   | `pnpm-lock.yaml` | pnpm |
   | `package-lock.json` or `npm-shrinkwrap.json` | npm |
   | `yarn.lock` | Yarn |
   | `bun.lock` or `bun.lockb` | Bun |

   If there is no lockfile, use the declared package manager or repository instructions; otherwise ask the user which manager to use.
3. Check for an existing Clicklore script, provider, plugin or `init()` call, including tag managers. Update that integration if present. Load the SDK once per page: use either npm or the script tag. A second SDK copy warns and remains inactive; it does not double count events.
4. Read an existing Clicklore project key from the app's environment configuration if one is already supplied. Otherwise ask the user for the public `cl_…` key from the project's **Settings** page in the [Clicklore dashboard](https://app.clicklore.com), where the install snippets are shown. Never invent a key or reuse a demo key. Every `cl_…` below is a placeholder to replace with that real key before verification.
5. Use `https://app.clicklore.com` as `host` for hosted Clicklore. For self-hosting, obtain the browser-accessible deployment base URL, `https://<DOMAIN>`. This is the dashboard origin serving `/sdk/clicklore.js` and ingest `/v1/b`; do not append those paths to `host` or use an internal Docker URL. Use that host in every example below, including script URLs and CSP.
6. Keep configuration in the app's existing environment mechanism. Prefer `NEXT_PUBLIC_CLICKLORE_KEY` for Next.js and `VITE_CLICKLORE_KEY` for Vite. The project key is public by design and will be visible in browser JavaScript; it is not a dashboard credential or server secret. Use an ignored local environment file where supported, and add empty variable names to an existing environment template if appropriate. Supply the same variables to deployment builds.

The five published packages are MIT licensed: `@clicklore/browser`, `@clicklore/react`, `@clicklore/vue`, `@clicklore/angular` and `@clicklore/annotate`. The browser SDK has no runtime dependencies. Each framework adapter re-exports its API and takes `@clicklore/browser` as a peer dependency: always install the browser package with the adapter, at the same resolved version. The commands below request both together; check their resolved versions afterward. If Clicklore is already installed, explicitly select the same release for both rather than mixing versions. Install `@clicklore/annotate` as a dev dependency.

React requires 18+, the Next.js integration requires Next.js 16+, the Vue adapter requires Vue 3.3+ (Vue and `@vue/compiler-sfc` 3.4+ for annotation), and Angular requires 19+ with `@angular/router`. Annotation requires Node.js `^20.19.0 || >=22.12.0`. Check these requirements before installing. Do not upgrade the app's framework just to fit an example; report incompatibilities and use a compatible browser SDK integration when appropriate.

In each command block, run only the group for the detected package manager. Adapt file extensions and import paths to the existing app. The complete file examples show minimal applications; merge the integration into existing files instead of replacing their other content.

## Next.js 16+ App Router

Install in the Next.js application workspace:

```sh
# pnpm
pnpm add @clicklore/browser @clicklore/react
pnpm add -D @clicklore/annotate

# npm
npm install @clicklore/browser @clicklore/react
npm install -D @clicklore/annotate

# Yarn
yarn add @clicklore/browser @clicklore/react
yarn add -D @clicklore/annotate

# Bun
bun add @clicklore/browser @clicklore/react
bun add -D @clicklore/annotate
```

Set these values in the app's `.env.local` or existing environment store:

```dotenv
NEXT_PUBLIC_CLICKLORE_KEY=cl_…
NEXT_PUBLIC_CLICKLORE_HOST=https://app.clicklore.com
```

Wrap the application children once in `app/layout.tsx` (or `src/app/layout.tsx`):

```tsx
import { Clicklore } from '@clicklore/react/next';
import type { ReactNode } from 'react';

export default function RootLayout({ children }: { children: ReactNode }) {
  return (
    <html lang="en">
      <body>
        <Clicklore
          projectKey={process.env.NEXT_PUBLIC_CLICKLORE_KEY!}
          host={process.env.NEXT_PUBLIC_CLICKLORE_HOST ?? 'https://app.clicklore.com'}
        >
          {children}
        </Clicklore>
      </body>
    </html>
  );
}
```

Keep the root layout as a server component. `Clicklore` supplies the client boundary, initializes capture, and reports App Router templates such as `/projects/[id]`. If the app needs function options such as `sanitizeUrl`, define those in a client component wrapping `Clicklore`; functions cannot be passed across the server-to-client boundary.

Wrap the existing configuration in `next.config.ts`:

```ts
import { withClicklore } from '@clicklore/annotate/next';
import type { NextConfig } from 'next';

const nextConfig: NextConfig = {
  // Keep all existing configuration here.
};

export default withClicklore(nextConfig);
```

`withClicklore` accepts any config object, including one annotated as `NextConfig`, and returns the same type. Preserve the actual config object and any existing config wrappers. Apply `withClicklore()` to the resolved config object if the existing export is a function or promise. The wrapper supports Turbopack and webpack and preserves existing hooks and rules. The published npm package already includes its loader.

For the Pages Router, use `ClickloreProvider` from `@clicklore/react` in `pages/_app.tsx` instead of `Clicklore`:

```tsx
import { ClickloreProvider } from '@clicklore/react';
import type { AppProps } from 'next/app';

export default function App({ Component, pageProps }: AppProps) {
  return (
    <ClickloreProvider
      projectKey={process.env.NEXT_PUBLIC_CLICKLORE_KEY!}
      host={process.env.NEXT_PUBLIC_CLICKLORE_HOST ?? 'https://app.clicklore.com'}
    >
      <Component {...pageProps} />
    </ClickloreProvider>
  );
}
```

The provider captures pathname changes and infers route templates. To supply actual Pages Router templates, call `setRoute(router.pathname)` from `@clicklore/react` in a client effect once the router is ready and after navigation. `withClicklore()` also annotates Pages Router JSX on Next.js 16+.

## Vite + React

```sh
# pnpm
pnpm add @clicklore/browser @clicklore/react
pnpm add -D @clicklore/annotate

# npm
npm install @clicklore/browser @clicklore/react
npm install -D @clicklore/annotate

# Yarn
yarn add @clicklore/browser @clicklore/react
yarn add -D @clicklore/annotate

# Bun
bun add @clicklore/browser @clicklore/react
bun add -D @clicklore/annotate
```

App `.env.local`:

```dotenv
VITE_CLICKLORE_KEY=cl_…
VITE_CLICKLORE_HOST=https://app.clicklore.com
```

`src/main.tsx`:

```tsx
import { ClickloreProvider } from '@clicklore/react';
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import App from './App';

createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <ClickloreProvider
      projectKey={import.meta.env.VITE_CLICKLORE_KEY}
      host={import.meta.env.VITE_CLICKLORE_HOST ?? 'https://app.clicklore.com'}
    >
      <App />
    </ClickloreProvider>
  </StrictMode>,
);
```

`vite.config.ts`: put annotation before the React compilation plugin. Keep the existing React plugin variant and other Vite options.

```ts
import { clickloreAnnotate } from '@clicklore/annotate/vite';
import react from '@vitejs/plugin-react';
import { defineConfig } from 'vite';

export default defineConfig({
  plugins: [clickloreAnnotate(), react()],
});
```

For React Router 6.4+, import `ClickloreRoutes` or `useClickloreRoutes` from `@clicklore/react/react-router`. Under the existing `BrowserRouter`, replace `Routes` with `ClickloreRoutes`, keeping its `Route` children. With `createBrowserRouter`, call `useClickloreRoutes(routes)` with the existing route config in a component that stays mounted inside the router, such as the root layout. These report patterns such as `/projects/:id`, including the basename. Do not create a second router. Hash routing is not supported; descendant routes under a splat report the parent pattern.

## Vue 3 with Vite

Use Vue 3.4+ for the full setup with annotation. The runtime adapter also supports Vue 3.3 without annotation. Vue Router is optional; when present it must be 4+.

```sh
# pnpm
pnpm add @clicklore/browser @clicklore/vue
pnpm add -D @clicklore/annotate

# npm
npm install @clicklore/browser @clicklore/vue
npm install -D @clicklore/annotate

# Yarn
yarn add @clicklore/browser @clicklore/vue
yarn add -D @clicklore/annotate

# Bun
bun add @clicklore/browser @clicklore/vue
bun add -D @clicklore/annotate
```

Ensure `@vue/compiler-sfc` is installed at the same version as the app's Vue, at least 3.4, for annotation. If missing, run the matching command below, replacing `<installed-vue-version>` with the actual installed version:

```sh
pnpm add -D "@vue/compiler-sfc@<installed-vue-version>"
npm install -D "@vue/compiler-sfc@<installed-vue-version>"
yarn add -D "@vue/compiler-sfc@<installed-vue-version>"
bun add -D "@vue/compiler-sfc@<installed-vue-version>"
```

App `.env.local`:

```dotenv
VITE_CLICKLORE_KEY=cl_…
VITE_CLICKLORE_HOST=https://app.clicklore.com
```

`src/main.ts`, using the app's existing router:

```ts
import { ClicklorePlugin } from '@clicklore/vue';
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';

const app = createApp(App);
app.use(router);
app.use(ClicklorePlugin, {
  projectKey: import.meta.env.VITE_CLICKLORE_KEY,
  host: import.meta.env.VITE_CLICKLORE_HOST ?? 'https://app.clicklore.com',
  router,
});
app.mount('#app');
```

If the app has no router, omit its import, `app.use(router)` and the `router` option; do not install a router solely for Clicklore. With a router, successful navigations report its templates. Hash history is not supported.

`vite.config.ts`: add `clickloreVue()` to the existing Vue compiler node transforms. Preserve other plugin and compiler options, including existing transforms.

```ts
import { clickloreVue } from '@clicklore/annotate/vue';
import vue from '@vitejs/plugin-vue';
import { defineConfig } from 'vite';

export default defineConfig({
  plugins: [
    vue({
      template: {
        compilerOptions: {
          nodeTransforms: [clickloreVue()],
        },
      },
    }),
  ],
});
```

For Nuxt, register `ClicklorePlugin` in `app/plugins/clicklore.client.ts` (Nuxt 4) or `plugins/clicklore.client.ts` (Nuxt 3), inside `defineNuxtPlugin`. Call `nuxtApp.vueApp.use(ClicklorePlugin, { projectKey, host, router: useRouter() })`, taking `projectKey` and `host` from the app's public runtime configuration. The `.client.ts` suffix keeps initialization in the browser. With Nuxt's Vite builder, add `clickloreVue()` to the top-level `vue.compilerOptions.nodeTransforms` array in `nuxt.config.ts`.

## Angular 19+

The adapter requires `@angular/common`, `@angular/core` and `@angular/router` 19+. Use the app's existing routing and bootstrap arrangement.

```sh
# pnpm
pnpm add @clicklore/browser @clicklore/angular

# npm
npm install @clicklore/browser @clicklore/angular

# Yarn
yarn add @clicklore/browser @clicklore/angular

# Bun
bun add @clicklore/browser @clicklore/angular
```

Use Angular's existing environment files, file replacements or generated public configuration. Prefer the app's existing environment-to-config mechanism for the key; Angular does not automatically expose `process.env` in browser code. A minimal `src/environments/environment.ts` is:

```ts
export const environment = {
  clickloreKey: 'cl_…',
  clickloreHost: 'https://app.clicklore.com',
};
```

Populate this with the real public key and deployment URL for each environment. Keep real server secrets out of all browser configuration.

`src/app/app.config.ts`:

```ts
import type { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideClicklore } from '@clicklore/angular';
import { environment } from '../environments/environment';
import { routes } from './app.routes';

export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(routes),
    provideClicklore({
      projectKey: environment.clickloreKey,
      host: environment.clickloreHost,
    }),
  ],
};
```

`src/main.ts`, if the app uses this bootstrap structure:

```ts
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app/app.component';
import { appConfig } from './app/app.config';

bootstrapApplication(AppComponent, appConfig).catch((error: unknown) => console.error(error));
```

Keep the app's actual root component name and imports. If it already supplies providers directly to `bootstrapApplication`, add `provideClicklore()` there instead. Register it once. Router templates are reported automatically when a router is provided; initialization also works without a router provider. `withHashLocation()` is not supported.

There is no Angular template annotation transform. Do not install `@clicklore/annotate` for Angular. Use `data-track="save-settings"` on important elements; other elements use the SDK's fallback identity.

## Plain HTML or any site

No package installation is needed for the script tag. Insert this classic script once in the existing document head, with the real project key:

```html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Application</title>
    <script src="https://app.clicklore.com/sdk/clicklore.js" data-key="cl_…" defer></script>
  </head>
  <body>
    <button data-track="open-settings">Settings</button>
  </body>
</html>
```

For self-hosting, change `src` to `https://<DOMAIN>/sdk/clicklore.js`. The script initializes itself and exposes `window.clicklore`.

| Attribute | Meaning |
| --- | --- |
| `data-key="cl_…"` | Public project key; enables automatic initialization. |
| `data-host="https://<DOMAIN>"` | Override the deployment base URL. Defaults to the script's origin; set explicitly if ingest is elsewhere or uses a reverse proxy path. |
| `data-mask-all-text` | Suppress element text labels. |
| `data-capture-input-values` | Opt into field values; add only if the user explicitly requests it. |
| `data-require-consent` | Wait for `optIn()` before capture. |
| `data-debug` | Log captured events for debugging. |

Boolean attributes are enabled by presence: `data-debug="false"` still enables debugging. Omit an attribute to leave it off.

If application code or the consent UI may call the API before the deferred SDK loads, replace the single SDK tag above with the following stub and tag, before application code. This example enables consent; omit `data-require-consent` if it is not needed. Keep only one SDK tag.

```html
<script>
  {
    const q = [];
    window.clicklore = { q };
    for (const name of ['track', 'identify', 'group', 'reset', 'setRoute', 'optIn', 'optOut']) {
      window.clicklore[name] = (...args) => q.push(sdk => sdk[name](...args));
    }
  }
</script>
<script src="https://app.clicklore.com/sdk/clicklore.js" data-key="cl_…" data-require-consent defer></script>
```

The SDK initializes from its tag and then replays queued calls in order. This queue stub supports the listed methods, not `init()`. For function options such as `sanitizeUrl`, omit `data-key` and call `window.clicklore.init(config)` after the script loads, for example from a `DOMContentLoaded` listener registered before the deferred tag runs.

Alternatively, for a bundled app without a framework adapter, use npm instead of the script tag:

```sh
# Run only the matching command.
pnpm add @clicklore/browser
npm install @clicklore/browser
yarn add @clicklore/browser
bun add @clicklore/browser
```

For example, in a plain Vite app, use the `VITE_CLICKLORE_KEY` and `VITE_CLICKLORE_HOST` environment values shown above and initialize in the existing client entry point, `src/main.ts`:

```ts
import { init } from '@clicklore/browser';

init({
  projectKey: import.meta.env.VITE_CLICKLORE_KEY,
  host: import.meta.env.VITE_CLICKLORE_HOST ?? 'https://app.clicklore.com',
});
```

For other bundlers, use their existing public environment mechanism. In an SSR app, use its client startup hook. Do not add a separate `init()` when an adapter already initializes the SDK.

## Identify users after login

Capture works anonymously without authentication integration. If the app has login, use its stable user ID after successful authentication. Traits are sent as supplied; include only approved profile properties.

For direct SDK integration, a complete helper module is:

```ts
import { identify, reset } from '@clicklore/browser';

export function identifySignedInUser(user: { id: string; plan: string }) {
  identify(user.id, { plan: user.plan });
}

export function resetSignedOutUser() {
  reset();
}
```

Call these helpers from the app's existing login/session-restoration and logout flows. Reset before identifying a different user. In React, Vue or Angular, import the same functions from that app's adapter package. For the script tag, use `window.clicklore.identify(user.id, { plan: user.plan })` and `window.clicklore.reset()` instead, using the queue stub when necessary.

In React or Next.js, the existing provider or `Clicklore` component can synchronize identity with `user={user ? { id: user.id, traits: { plan: user.plan } } : null}`. Pass `null` on logout; changing to another user resets the previous identity automatically. Use a client wrapper if auth state comes from a client hook, and keep only one Clicklore provider. Configuration is fixed at first initialization; `user` is synchronized separately.

Vue's plugin accepts `user` as a ref, computed or getter of `{ id, traits? } | null`. Angular accepts a `user` factory returning a signal of that shape, for example `user: () => inject(AuthService).user` when that is the app's actual auth service and signal. Both synchronize identification and reset on logout or account changes. Choose either adapter synchronization or explicit auth callbacks.

## Name elements and control capture

Use stable, non-sensitive names such as `data-track="export-csv"`. Element identity prefers `data-track`, then build-generated `data-cl` annotations, then a fallback from the route, element kind, accessible label and stable selector. Annotation supplies component/source information without manually naming every element.

| Attribute | Effect |
| --- | --- |
| `data-track="save-settings"` | Explicit element name. |
| `data-cl-mask` | Suppress text labels and field values on an element and its descendants. |
| `data-cl-ignore` | Skip element interactions on an element and its descendants. |
| `data-cl-capture` | Opt into this field's value, even when global input-value capture is off. |

For example:

```html
<button data-track="save-settings">Save settings</button>
<section data-cl-mask>Private account details</section>
<section data-cl-ignore>Interactions in this section are excluded</section>
```

Leave input-value capture off unless the user asks for it. Only then add `data-cl-capture` to specifically approved non-sensitive fields, or enable `captureInputValues: true` if broad capture is explicitly requested. Never mark passwords, payment information, one-time codes, tokens or other sensitive fields for capture. The SDK also blocks sensitive fields and redacts captured text by default; this does not replace reviewing the app's chosen fields and user traits.

## Consent

If the app requires analytics consent, configure it at the initial setup: add `requireConsent: true` to `init()`, `ClicklorePlugin` or `provideClicklore()` options, add the `requireConsent` prop to `ClickloreProvider` or `Clicklore`, or add `data-require-consent` to the script tag. Reuse the app's consent UI and stored choice.

Connect its acceptance and rejection/withdrawal handlers to these functions, for example in `src/analytics-consent.ts`:

```ts
import { optIn, optOut } from '@clicklore/browser';

export function acceptAnalytics() {
  optIn();
}

export function declineAnalytics() {
  optOut();
}
```

Use the adapter's re-exports in framework apps, or `window.clicklore.optIn()` / `window.clicklore.optOut()` for the script tag. Do not call `optIn()` unconditionally. While waiting for consent, the SDK sends no events and writes nothing to `localStorage`. `optOut()` stops capture, drops queued and unsent data, and removes stored identifiers. The consent choice is remembered across reloads.

## CSP and allowed origins

Preserve the app's existing Content Security Policy. Add the Clicklore deployment origin to `connect-src` so fetch and beacons can reach `{host}/v1/b`. For the script tag, also permit the script origin in `script-src`, or authorize the tag using the app's CSP nonce mechanism. Give the inline queue stub a nonce or hash when inline scripts are restricted. Bundled npm installs use the app's normal JavaScript policy.

For hosted Clicklore, these are the directive additions to merge into the existing policy:

```text
connect-src 'self' https://app.clicklore.com;
script-src 'self' https://app.clicklore.com;
```

Use the actual self-hosted origin instead when applicable, or `'self'` for same-origin ingest. Do not replace an existing policy with this fragment or enable unrestricted inline scripts.

In the project's **Settings**, check the origin allowlist. Include the capturing application's actual development and production origins, with scheme and port where applicable, such as `http://localhost:3000` and `https://your-app.example`. These are the app's origins, not the Clicklore dashboard origin. If you cannot access project settings, tell the user exactly which origins need adding.

## Verify

1. Check that the selected adapter and `@clicklore/browser` resolve to the same version, annotation is a dev dependency where applicable, and there is only one SDK installation on each page. Check the key and host are populated for the environment being tested. Restart the dev server after changing environment or bundler configuration.
2. Run the app with its existing script. For a `dev` script, use the matching command:

   ```sh
   pnpm run dev
   npm run dev
   yarn run dev
   bun run dev
   ```

   Angular apps commonly use `start` instead: `pnpm run start`, `npm run start`, `yarn run start` or `bun run start`. Use the actual script in `package.json` and the existing workspace invocation.
3. Open the app, click buttons and links, navigate between routes, and exercise an ordinary form without enabling value capture. With consent required, confirm no ingest requests or SDK storage writes occur while awaiting a choice; accept through the actual consent UI, then repeat the interactions.
4. In browser developer tools, look for `POST {host}/v1/b` (possibly with `?z=1`). A successful ingest responds with HTTP 204. If it fails, check the project key, deployment URL, origin allowlist, CSP and browser blocking before changing the integration.
5. Open that project's **Live** view in the dashboard and confirm the interactions arrive. Check **Overview** for activity in the current date range. If annotation was configured, inspect an interactive element for its generated `data-cl` attribute and confirm component/source information is available. If auth was integrated, verify login and logout identity behavior.
6. For troubleshooting, temporarily set `debug: true` in SDK/plugin/provider options, add the `debug` prop on the React component, or add `data-debug` on the script tag. It logs captured events and warns about batches dropped after HTTP 4xx responses. Local logs alone do not prove delivery. Remove temporary debugging after verification, and run the repository's relevant existing checks.

Report the detected framework and package manager, installed packages and versions, changed files, environment variable names and host, verification actually performed, and any remaining dashboard or deployment steps. If the key, browser access or dashboard access is missing, state precisely what remains unverified; do not claim events arrived.

## Do not

- Do not capture input values unless the user explicitly asks.
- Never add sensitive fields to `data-cl-capture`.
- Do not install a script tag and the npm SDK together, or add a second provider/initializer.
- Do not invent a project key, adapter API or configuration option.
- Do not commit secrets. The project key is public, but keep it in the app's environment configuration; dashboard credentials, database passwords and server API keys must never enter browser code.

## References

- [Browser SDK](https://github.com/clicklore/clicklore/tree/main/packages/browser#readme)
- [React, Next.js and React Router](https://github.com/clicklore/clicklore/tree/main/packages/react#readme)
- [Vue and Nuxt](https://github.com/clicklore/clicklore/tree/main/packages/vue#readme)
- [Angular](https://github.com/clicklore/clicklore/tree/main/packages/angular#readme)
- [Build-time annotation](https://github.com/clicklore/clicklore/tree/main/packages/annotate#readme)
- [Architecture](https://github.com/clicklore/clicklore/blob/main/docs/architecture.md)
- [Self-hosting](https://github.com/clicklore/clicklore/blob/main/docs/self-hosting.md)
