virling Pricing Self-host Demo Changelog Agencies GitHub Start free trial
blog / 2026-11-24

Angular Stripe UTM tracking: pass UTMs to Stripe Checkout

By Devendra Variya, co-founder of Virling. Published 2026-11-24, updated 2026-11-27.

In Angular, a service that injects HttpClient reads the visitor ID, posts it to your backend, and the backend sets it as metadata.virling_vid on the Stripe Checkout Session. With server-side rendering, that backend can be the Express server in src/server.ts that already renders your pages.

Stripe's hosted checkout never sees the UTM tags of the landing URL, so the Virling script records them under the visitor ID, and Virling matches the payment to the visits behind it. The general guide to Stripe Checkout UTM parameters covers Payment Links, metadata limits and where the values show up in Stripe. The code follows the Angular 22 docs linked in each section.

Start free trial

The script tag in src/index.html

src/index.html is the main HTML page of the app (Angular file structure). Paste the tag before </head>, with your Virling server in place of app.virling.com if you self-host.

<!-- src/index.html -->
<script defer src="https://app.virling.com/v.js"
  data-site="yourdomain.com"></script>

Angular strips <script> from component templates (Angular templates), and the scripts array of angular.json bundles the file, after which it cannot read data-site from its own tag. The plain tag in src/index.html is the one place that works.

A Checkout service with HttpClient

The script loads with defer, so the service waits for it for up to two seconds. window.virling?.vid?.() returns null in cookieless mode and nothing when the script is blocked, and the service sends null in both cases:

// src/app/checkout.ts
import { HttpClient } from "@angular/common/http";
import { Injectable, inject } from "@angular/core";
import { from, switchMap } from "rxjs";

declare global {
  interface Window {
    virling?: { vid?: () => string | null };
  }
}

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

  start() {
    return from(this.visitorId()).pipe(
      switchMap((vid) => this.http.post<{ url: string }>("/api/checkout", { vid })),
    );
  }

  private async visitorId() {
    for (let i = 0; i < 20 && !window.virling?.vid; i++) {
      await new Promise((r) => setTimeout(r, 100));
    }
    return window.virling?.vid?.() || null;
  }
}

In Angular 21 and later HttpClient can be injected by default. In earlier versions, add provideHttpClient() to the providers in app.config.ts (HttpClient setup). The newer @Service() decorator is a shorthand for @Injectable({ providedIn: "root" }) (Angular services); use either.

The button calls the service and subscribes, since HttpClient sends nothing until something does (HttpClient requests):

// src/app/buy-button.ts
import { Component, inject, signal } from "@angular/core";
import { Checkout } from "./checkout";

@Component({
  selector: "app-buy-button",
  template: `<button type="button" [disabled]="busy()" (click)="buy()">Buy</button>`,
})
export class BuyButton {
  private checkout = inject(Checkout);
  protected readonly busy = signal(false);

  protected buy() {
    this.busy.set(true);
    this.checkout.start().subscribe({
      next: ({ url }) => {
        window.location.href = url;
      },
      error: () => this.busy.set(false),
    });
  }
}

Router events and pageviews

The Angular router updates the address bar through Location, which with the default PathLocationStrategy calls history.pushState, or history.replaceState when you pass replaceUrl. The Virling script hooks those calls and popstate, so there is no need to subscribe to router.events and report each NavigationEnd (single-page apps). A route change carries no referrer and stays in the channel of the landing page.

  • queryParamsHandling. By default a routerLink replaces the current query parameters with its own (QueryParamsHandling), so the tags leave the URL on the first click. The script recorded them with the landing pageview, so "preserve" on every link is not needed.
  • Redirects and guards. The router writes the URL once a navigation succeeds, so a redirectTo route or a guard that returns a UrlTree is counted once, at its final address.
  • skipLocationChange. A navigation with skipLocationChange: true leaves the URL alone, so that view is not counted.
  • Hash URLs. With withHashLocation() or HashLocationStrategy the path never changes, so only the first page is counted (Angular routing tasks).

The checkout route in server.ts

Angular Universal became the @angular/ssr package in Angular 17. ng new --ssr, or ng add @angular/ssr on an existing app, sets up the application builder with an Express server in src/server.ts (Angular SSR). Its generated comments leave room for API routes above the static file and render handlers, so the checkout route can run in the same Node process, on the same origin as the pages:

// src/server.ts, above express.static and the AngularNodeAppEngine handler
import Stripe from "stripe";

const stripe = new Stripe(process.env["STRIPE_SECRET_KEY"]!);
const appUrl = process.env["APP_URL"] ?? "http://localhost:4000";

app.post("/api/checkout", express.json(), async (req, res) => {
  const vid = String(req.body?.vid ?? "");
  const session = await stripe.checkout.sessions.create({
    mode: "subscription",
    line_items: [{ price: process.env["STRIPE_PRICE_ID"], quantity: 1 }],
    success_url: `${appUrl}/thanks`,
    metadata: /^[A-Za-z0-9-]{8,64}$/.test(vid) ? { virling_vid: vid } : {},
  });
  res.json({ url: session.url });
});

Install the library with npm install stripe; Express is already a dependency of the SSR setup (Stripe API reference). The environment keys use brackets because the generated tsconfig.json turns on noPropertyAccessFromIndexSignature, the reason the template itself reads process.env['PORT']. Only the server knows the price, and the pattern test drops any vid that does not look like a Virling ID before it reaches Stripe.

The service is safe under SSR and hydration: it touches window only inside start(), which runs on a click in the browser and never during the server render. Apps still on Angular Universal have a similar server.ts built around ngExpressEngine, and the route goes in it the same way. Without SSR, put the route in any Node server and proxy /api to it from ng serve with a proxyConfig file (Angular CLI serve).

Test the SSR build

The route is easiest to check against a production build, served by the same server.ts that runs in production:

  1. Add data-dev to the tag, since the script skips localhost without it, and set data-site to a test site of yours, connected in Virling to a restricted Stripe key that starts with rk_test_.
  2. Run ng build, then STRIPE_SECRET_KEY=sk_test_... STRIPE_PRICE_ID=price_... npm run serve:ssr:my-app, the script ng add @angular/ssr puts in package.json under your project's name. It listens on port 4000.
  3. In a private window, open http://localhost:4000/?utm_source=test&utm_medium=test, follow a routerLink and click Buy.
  4. Pay with 4242 4242 4242 4242, any future date and any CVC (Stripe testing), wait for the next sync, and the payment shows the test source in Virling.

Before you deploy, remove data-dev, point data-site back at your domain and set APP_URL. The full checklist is in test your setup.

Usual mistakes

  • The ID is read in a constructor. At startup the script may not have run, and during the server render window does not exist. Read it on click, as the service does.
  • Nothing subscribes to the request. this.http.post() alone sends nothing.
  • The secret key is in environment.ts. Environment files are compiled into the browser bundle. Keep the key in the environment of the Node process that runs server.ts.
  • The ID is only in subscription_data.metadata. That goes to the subscription, which Virling does not read. Set metadata on the session itself.

If a payment still shows Unattributed, check that window.virling.vid() returns an ID in the console, that the request to /api/checkout carries it, and that the session in Stripe has virling_vid in its metadata. How the join works is in how to track Stripe revenue by traffic source. With a separate backend, see Express Stripe UTM tracking or NestJS Stripe UTM tracking, and for React, React Stripe UTM tracking.

Frequently asked questions

How do I pass UTM parameters to Stripe Checkout from an Angular app?

Send the visitor ID, not the tags. A service reads it with window.virling?.vid?.(), posts it with HttpClient to the route that creates the Checkout Session, and the route sets it as metadata.virling_vid. Virling already holds the UTM tags of each visit under that ID.

Do I need to send a pageview on NavigationEnd?

No. The router changes the URL through Location, which calls history.pushState or history.replaceState, and the Virling script hooks both. Each route with a new path or query string is one pageview.

Does the checkout service break server-side rendering?

No. It reads window only inside start(), which runs on a click in the browser, so the server render never calls it. The checkout route in server.ts runs in Node, where the Stripe secret key stays off the client.

Should I keep the tags in the URL with queryParamsHandling?

Not for attribution. The script records the tags with the landing pageview, so the router can drop them on the next navigation. Use queryParamsHandling only if your own code reads them later.

Can I put the visitor ID in subscription_data.metadata?

Not for Virling. It reads the charge, its PaymentIntent and the Checkout Session, not the metadata of the subscription. Set metadata.virling_vid on the session itself.

See which campaigns bring Stripe revenue

Virling is open source under AGPL. Self-host it free, or use the hosted version with a 14-day free trial. It connects to Stripe, Paddle, Shopify, WooCommerce, Polar, LemonSqueezy, Dodo, Creem and RevenueCat.

Start free trial See the demo