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

NestJS Stripe UTM tracking: Checkout metadata from a controller

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

In NestJS, the visitor ID gets to Stripe through pieces a Nest app already has: a controller that reads the virling_vid cookie, a CheckoutService that calls Stripe, and a module that provides the Stripe client to it. This post wires them up on the default Express platform with the stripe Node library, adds a unit test for the service, and sets up the raw body a Stripe webhook needs in Nest.

Stripe Checkout runs on Stripe's domain, so the UTM tags of your landing page never reach it on their own. The Virling script keeps them against a visitor ID in a first-party cookie, and Virling joins each payment that carries that ID in client_reference_id or metadata.virling_vid to the visits behind it. Payment Links, metadata limits and where the values appear in Stripe are in the guide to Stripe Checkout UTM parameters; the plain Express version is Express Stripe UTM tracking, and the App Router one is Next.js Stripe UTM tracking.

Start free trial

Where the script tag goes

Nest renders no HTML until you add a view engine, so the tag usually belongs in the frontend that serves your pages. With app.setBaseViewsDir() and a view engine, put it in the shared layout; with ServeStaticModule, put it in the built index.html. Self-hosted Virling users point src at their own server.

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

Provide the Stripe client

Register the client once as a provider, so services receive it by injection and tests can swap it for a fake. A symbol token keeps it apart from your other providers:

// src/checkout/stripe.provider.ts
import Stripe from "stripe";

export const STRIPE = Symbol("STRIPE");

export const stripeProvider = {
  provide: STRIPE,
  useFactory: () => new Stripe(process.env.STRIPE_SECRET_KEY!),
};
// src/checkout/checkout.module.ts
import { Module } from "@nestjs/common";
import { CheckoutController } from "./checkout.controller";
import { CheckoutService } from "./checkout.service";
import { stripeProvider } from "./stripe.provider";

@Module({
  controllers: [CheckoutController],
  providers: [stripeProvider, CheckoutService],
})
export class CheckoutModule {}

With @nestjs/config, add inject: [ConfigService] to the provider and read the key with config.getOrThrow("STRIPE_SECRET_KEY") inside the factory instead of process.env.

The CheckoutService

The service takes the visitor ID as a plain argument and never sees the request:

// src/checkout/checkout.service.ts
import { Inject, Injectable } from "@nestjs/common";
import Stripe from "stripe";
import { STRIPE } from "./stripe.provider";

@Injectable()
export class CheckoutService {
  constructor(@Inject(STRIPE) private readonly stripe: Stripe) {}

  async createSession(vid?: string): Promise<string> {
    const session = await this.stripe.checkout.sessions.create({
      mode: "subscription",
      line_items: [{ price: "price_...", quantity: 1 }],
      success_url: "https://yourdomain.com/thanks",
      client_reference_id: vid,
    });
    return session.url!;
  }
}

An undefined vid is dropped from the request by the stripe library, so a buyer without the cookie still gets a session. If client_reference_id already holds your user ID, give createSession that ID as another argument and pass the visitor ID as metadata: vid ? { virling_vid: vid } : undefined, which Virling reads before client_reference_id.

Read the cookie in the controller

On the Express platform, Nest leaves req.cookies unset until cookie-parser runs. Install cookie-parser and @types/cookie-parser and register it in main.ts; the rawBody option is for the webhook further down:

// src/main.ts
import { NestFactory } from "@nestjs/core";
import type { NestExpressApplication } from "@nestjs/platform-express";
import cookieParser from "cookie-parser";
import { AppModule } from "./app.module";

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule, { rawBody: true });
  app.use(cookieParser());
  await app.listen(3000);
}
bootstrap();

Instead of injecting the whole @Req(), a small param decorator returns just the visitor ID, so the handler declares only what it uses:

// src/checkout/visitor-id.decorator.ts
import { createParamDecorator, ExecutionContext } from "@nestjs/common";
import type { Request } from "express";

export const VisitorId = createParamDecorator(
  (_data: unknown, ctx: ExecutionContext): string | undefined =>
    ctx.switchToHttp().getRequest<Request>().cookies?.virling_vid,
);
// src/checkout/checkout.controller.ts
import { Controller, Post, Redirect } from "@nestjs/common";
import { CheckoutService } from "./checkout.service";
import { VisitorId } from "./visitor-id.decorator";

@Controller("checkout")
export class CheckoutController {
  constructor(private readonly checkout: CheckoutService) {}

  @Post()
  @Redirect()
  async create(@VisitorId() vid?: string) {
    return { url: await this.checkout.createSession(vid), statusCode: 303 };
  }
}

A guard gets the same request from context.switchToHttp().getRequest(). If checkout sits behind an auth guard, that guard can read cookies.virling_vid too, for example to log buyers who arrive without one, but the Stripe call stays in the service. Post a plain HTML form to /checkout, so the browser itself follows the 303 to checkout.stripe.com.

Stripe webhooks need the raw body

Virling reads payments with a restricted key and needs no webhook from you. If your app has its own, for example to unlock an account, Nest's JSON parser reaches the request first, and constructEvent() fails on the parsed object because Stripe signs the exact bytes it sent. With rawBody: true in main.ts, Nest keeps a Buffer on req.rawBody while @Body() keeps working elsewhere:

// src/checkout/webhook.controller.ts
import { BadRequestException, Controller, Headers, Inject, Post, RawBodyRequest, Req } from "@nestjs/common";
import type { Request } from "express";
import Stripe from "stripe";
import { STRIPE } from "./stripe.provider";

@Controller("stripe/webhook")
export class WebhookController {
  constructor(@Inject(STRIPE) private readonly stripe: Stripe) {}

  @Post()
  handle(@Req() req: RawBodyRequest<Request>, @Headers("stripe-signature") sig: string) {
    let event: Stripe.Event;
    try {
      event = this.stripe.webhooks.constructEvent(req.rawBody!, sig, process.env.STRIPE_WEBHOOK_SECRET!);
    } catch {
      throw new BadRequestException("bad signature");
    }
    // act on event.type here
    return { received: true };
  }
}

Add WebhookController to the module's controllers. Throwing BadRequestException makes Nest answer 400 instead of the 500 an uncaught error would give, so Stripe's delivery log shows the real cause.

A frontend on another origin

A Nest API on api.yourdomain.com still receives the cookie from a page on www.yourdomain.com, because the script sets it on the parent domain. Call app.enableCors({ origin: "https://www.yourdomain.com", credentials: true }) and send the request with credentials: "include"; origin: true reflects every origin and should not be paired with credentials. For an API on an unrelated domain, read window.virling.vid() in the browser, post it, take it with @Body("vid") vid?: string, and return { url } for the page to open instead of using @Redirect().

Test the service without Stripe

Because the client is a provider, a Jest test can override the token and check what the service sends:

// src/checkout/checkout.service.spec.ts
import { Test } from "@nestjs/testing";
import { CheckoutService } from "./checkout.service";
import { STRIPE } from "./stripe.provider";

it("passes the visitor ID to Stripe", async () => {
  const create = jest.fn().mockResolvedValue({ url: "https://checkout.stripe.com/test" });
  const moduleRef = await Test.createTestingModule({
    providers: [CheckoutService, { provide: STRIPE, useValue: { checkout: { sessions: { create } } } }],
  }).compile();

  await moduleRef.get(CheckoutService).createSession("vid_123");
  expect(create).toHaveBeenCalledWith(expect.objectContaining({ client_reference_id: "vid_123" }));
});

For the whole path, connect a restricted key starting with rk_test_ in Virling, use a test-mode price, and make one tagged visit and one payment as in test your setup. The payment should show the visit's source; renewals then keep that channel with no code, as in renewals. If it shows as Unattributed, open it and look for Visitor under Details.

Common mistakes

SymptomCauseFix
@VisitorId() is always undefinedcookie-parser is not registered, and cookies?. hides the errorCall app.use(cookieParser()) in main.ts before app.listen (Nest cookies)
cookieParser fails with This expression is not callable, or at startup with cookie_parser_1.default is not a functionThe import style does not match esModuleInterop in tsconfig.jsonTurn esModuleInterop on, as new Nest projects do, and use the default import (esModuleInterop)
Build error TS1272 on @Req() req: RawBodyRequest<Request>With isolatedModules and emitDecoratorMetadata, a type in a decorated signature must be imported as a typeWrite import type { Request } from "express" (Nest request object)
Nest can't resolve dependencies of the CheckoutService (?)The service injects STRIPE, but stripeProvider is not in the module's providersAdd it there, or export it from a shared module that this one imports (Nest custom providers)
req.rawBody is undefined in the webhookrawBody: true is missing from NestFactory.createAdd it to the options in main.ts (Nest raw body, Stripe signature docs)
The checkout request never endsThe handler also injects @Res(), so Nest leaves the response to you and ignores @Redirect()Remove @Res(), or use @Res({ passthrough: true }) (Nest controllers)
Build error that relative imports need file extensionsThe project is ESM, with "type": "module" in package.jsonImport ./checkout.service.js and the like, with .js also for TypeScript files (Nest migration guide)
After paying, the buyer lands on an http:// or internal addresssuccess_url is built from req.protocol and req.hostname behind a proxy Nest does not trustOn a NestExpressApplication, call app.set("trust proxy", "loopback") for a proxy on the same machine, or use a fixed URL as above (Nest proxies)
app.use(cookieParser()) has no effectThe app runs on the Fastify adapter, where Express middleware such as cookie-parser does not parse cookiesRegister @fastify/cookie and read request.cookies from the Fastify request (Nest cookies)
No visitor ID though the browser has the cookiecreateSession is called from a queue processor or the webhook controller, where no buyer cookie existsRead the ID in the controller the browser posts to and pass it along (link checkout to visits)
No cookie while running Nest locallyThe script skips localhost and 127.* unless the tag has data-devAdd data-dev during development, and check the full flow on a subdomain of your site

Keep POST /checkout out of any cache and make sure no proxy drops the Cookie header (page caching and CDNs). Payments made before a fix usually stay Unattributed, so test with a fresh one.

Frequently asked questions

How do I pass UTM parameters to Stripe Checkout in NestJS?

Have the checkout controller read the virling_vid cookie, through req.cookies or a small param decorator, and hand it to the service that calls stripe.checkout.sessions.create as client_reference_id. Virling stores the UTM tags of each visit against that ID and joins the payment to them.

Why is req.cookies undefined in NestJS?

On the Express platform Nest does not parse cookies. Register cookie-parser with app.use(cookieParser()) in main.ts before app.listen. On the Fastify platform, register @fastify/cookie instead.

Where should the Stripe client live in a NestJS app?

In a provider, built once by a factory and injected into CheckoutService with @Inject. The app then shares one client, and tests replace it with a fake through the same token.

How do I verify Stripe webhook signatures in NestJS?

Create the app with rawBody: true, type the request as RawBodyRequest<Request>, and pass req.rawBody with the stripe-signature header to stripe.webhooks.constructEvent(). The parsed @Body() no longer matches the bytes Stripe signed. Virling itself needs no webhook.

What if client_reference_id already holds my user ID?

Put the visitor ID in the session's metadata.virling_vid, which Virling checks before client_reference_id, and keep your user ID where it is.

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