# Install on Angular

> Add MetricRaven to an Angular app through src/index.html or the @metricraven/web package, then track goals, identify users and attribute revenue.

Source: https://metricraven.com/docs/install-angular  
Markdown: https://metricraven.com/docs/install-angular.md  
Section: Installation guides

An Angular CLI app serves one `src/index.html` for every route, and server-rendered or prerendered pages are built from it too, so one tag there covers the whole app. The Angular Router changes pages with the history API by default, which the tracker follows without extra code.

## Add the script tag

1. **Copy your snippet**

   In MetricRaven, open your site's **Settings → Tracking & install → Install** card and copy the script tag. It already contains your site ID.

2. **Paste it into src/index.html before \</head>**

   Replace `YOUR_SITE_ID` with the public site ID from your site's **Settings → Tracking & install → Install** card. The site ID is public and safe in browser code; never put your secret key in a page.

   ```html title="src/index.html"
   <!-- src/index.html -->
   <!doctype html>
   <html lang="en">
     <head>
       <meta charset="utf-8" />
       <title>MyApp</title>
       <base href="/" />
       <meta name="viewport" content="width=device-width, initial-scale=1" />
       <link rel="icon" type="image/x-icon" href="favicon.ico" />
       <script
         defer
         src="https://metricraven.com/js/script.js"
         data-site-id="YOUR_SITE_ID"
       ></script>
     </head>
     <body>
       <app-root></app-root>
     </body>
   </html>
   ```

   Keep your existing file and add only the `<script>` element. `ng build` copies it into the built `index.html` unchanged.

3. **Build, deploy and open your app**

   `ng serve` runs on `localhost:4200`, which is not tracked by default; check the deployed app.

> **Verify it works**
>
> Open your live website in a normal browser window (not an automated or embedded one). In the browser's Network panel, look for `script.js` and then a request to `/api/v1/collect` whose response contains `ok: true`. Open your site's **Traffic** tab and choose **Refresh**; the selected dates must include your visit.
>
> Nothing showing? See [Troubleshooting](https://metricraven.com/docs/troubleshooting).

## Route changes

With the default router setup, each navigation calls `history.pushState`, and the tracker records it as a pageview, including back and forward. Changing only the query string, or a redirect that keeps the same path, doesn't add another view. Don't also call `pageview()` from `Router.events`: that counts every navigation twice. To record virtual screens yourself instead, see [SPA & virtual pages](https://metricraven.com/docs/spa-virtual-pages).

## Goals from a component or service

Wrap the tag in a small injectable service. It queues calls made before the script loads and does nothing during server rendering, where there is no `window`.

```typescript title="src/app/analytics.ts"
// src/app/analytics.ts
import { Injectable, PLATFORM_ID, inject } from "@angular/core";
import { isPlatformBrowser } from "@angular/common";

type Props = Record<string, string | number | boolean>;
type Traits = { name?: string; email?: string; image?: string; [trait: string]: unknown };
type Tracker = { q?: unknown[][]; [method: string]: unknown };

declare global {
  interface Window {
    analytics?: Tracker;
  }
}

/** Calls the MetricRaven tag. Calls made before it loads are queued; on the server they do nothing. */
@Injectable({ providedIn: "root" })
export class Analytics {
  private readonly browser = isPlatformBrowser(inject(PLATFORM_ID));

  track(name: string, props: Props = {}) {
    this.call("track", name, props);
  }

  identify(userId: string, traits: Traits = {}) {
    this.call("identify", userId, traits);
  }

  reset() {
    this.call("reset");
  }

  /** null on the server and until the tracker's first response. */
  visitorId(): string | null {
    if (!this.browser) return null;
    const getVisitorId = window.analytics?.["getVisitorId"];
    return typeof getVisitorId === "function" ? getVisitorId() : null;
  }

  private call(method: string, ...args: unknown[]) {
    if (!this.browser) return;
    const fn = window.analytics?.[method];
    if (typeof fn === "function") {
      fn(...args);
    } else {
      window.analytics = window.analytics || { q: [] };
      (window.analytics.q ||= []).push([method, ...args]);
    }
  }
}
```

Inject it where something worth counting happens:

```typescript title="src/app/pricing/pricing.ts"
// src/app/pricing/pricing.ts
import { Component, inject } from "@angular/core";
import { Analytics } from "../analytics";

@Component({
  selector: "app-pricing",
  template: `<button (click)="upgrade('pro')">Upgrade</button>`,
})
export class Pricing {
  private readonly analytics = inject(Analytics);

  upgrade(plan: string) {
    this.analytics.track("checkout_started", { plan });
  }
}
```

Goal names start with a letter, with up to 10 properties. For clicks you can also skip code and add `data-goal` attributes to the template; see [Goals & funnels](https://metricraven.com/docs/goals-funnels).

## Identify signed-in users

Call `identify` with your own stable user ID after sign-in, for example from your auth service, so goals, payments and visits on other devices join one journey. See [Link users to visits](https://metricraven.com/docs/identify-users), including signed identify for verified users.

```typescript title="Your auth service or component"
// After sign-in, and on page loads while signed in, with your own user ID.
this.analytics.identify(user.id, { name: user.name, email: user.email, plan: user.plan });

// On logout: forget the identify state.
this.analytics.reset();
```

## Attribute revenue

First [connect your payment provider](https://metricraven.com/docs/connect-payment-provider). Then, when a visitor starts checkout, send the visitor ID to the endpoint that creates the checkout, which copies it into the payment's metadata. Each payment is then credited to the visit that brought the customer.

```typescript title="src/app/checkout.ts"
// src/app/checkout.ts
import { Injectable, inject } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { firstValueFrom } from "rxjs";
import { Analytics } from "./analytics";

@Injectable({ providedIn: "root" })
export class Checkout {
  private readonly http = inject(HttpClient);
  private readonly analytics = inject(Analytics);

  /** Your own endpoint creates the checkout and copies visitorId into the payment's metadata. */
  async start(plan: string) {
    const { url } = await firstValueFrom(
      this.http.post<{ url: string }>("/api/checkout", { plan, visitorId: this.analytics.visitorId() }),
    );
    window.location.assign(url);
  }
}
```

For the server side, see [Stripe Checkout](https://metricraven.com/docs/stripe-checkout) or the [Payments API](https://metricraven.com/docs/payments-api). When you can't pass the visitor ID, credit a payment by the buyer's email instead: [Attribute by email](https://metricraven.com/docs/attribute-by-email).

## With the npm package

Instead of the tag and the service, you can install [@metricraven/web](https://metricraven.com/docs/npm-package): typed functions you import anywhere, safe during server rendering. Use the package or the tag, not both.

1. **Install it**

   ```bash title="Terminal"
   npm install @metricraven/web
   ```

2. **Call init once at startup**

   Replace `YOUR_SITE_ID` with the public site ID from your site's **Settings → Tracking & install → Install** card. The site ID is public and safe in browser code; never put your secret key in a page.

   ```typescript title="src/app/app.config.ts"
   // src/app/app.config.ts
   import { ApplicationConfig, provideAppInitializer } from "@angular/core";
   import { provideRouter } from "@angular/router";
   import { init } from "@metricraven/web";
   import { routes } from "./app.routes";

   export const appConfig: ApplicationConfig = {
     providers: [
       provideRouter(routes),
       // Loads the tracker once in the browser; does nothing during server rendering.
       provideAppInitializer(() => {
         init({ siteId: "YOUR_SITE_ID" });
       }),
     ],
   };
   ```

   In an `NgModule` app, add the same `provideAppInitializer` call to the root module's `providers`.

3. **Track, identify and read the visitor ID**

   ```typescript title="Any component or service"
   import { track, identify, reset, getVisitorId } from "@metricraven/web";

   track("checkout_started", { plan: "pro" });
   identify(user.id, { name: user.name, email: user.email });
   reset(); // on logout
   const visitorId = getVisitorId(); // null until the first response
   ```

## Notes

- To serve the script from your own domain, see [Managed proxy](https://metricraven.com/docs/managed-proxy) or [Use your own domain](https://metricraven.com/docs/proxy).
- If your app sets a Content Security Policy, allow `https://metricraven.com` in `script-src` and `connect-src`. See [Script blocked by Content Security Policy (CSP)](https://metricraven.com/docs/content-security-policy).

## Questions

### Can I add the script from a component?

It's better not to. A component can be created more than once, and each copy of the script counts every page again. The tag in `src/index.html`, or `init` in an app initializer, runs exactly once.

### My router uses hash URLs (/#/pricing). What changes?

With `withHashLocation()` (or `useHash: true`), the route sits after `#`, which the tracker ignores by default. Turn on hash routes so each `#/` route counts as a page.

```typescript title="src/app/app.config.ts"
// src/app/app.config.ts
provideRouter(routes, withHashLocation()); // URLs like /#/pricing

// With the tag: add data-track-hash="true" to it.
// With the npm package: init({ siteId: "YOUR_SITE_ID", hashRouting: true });
```

### Can each environment use its own site ID?

With the npm package, read the site ID from your `environment.ts` files, which `fileReplacements` swaps per build configuration. With the tag, point a build configuration at its own copy of the index file with the `index` option; the output is still `index.html`. The site ID is public, so this is about switching sites, not secrecy.

```json title="angular.json"
// angular.json (projects → your app → architect → build → configurations)
"staging": {
  "index": { "input": "src/index.staging.html", "output": "index.html" }
}
```

Optional script attributes are listed in [Install & verify](https://metricraven.com/docs/install). To exclude your own visits, see [Exclude your visits](https://metricraven.com/docs/exclude-visits).
