Skip to content

Install the storefront consent adapter

Use one installation per verified HTTPS storefront origin, organization and commerce environment. The platform stores the shopper’s analytics choice for your storefront. Your storefront supplies the controls' mount point, its privacy policy and its approved GA4 loader. A merchant consent database is unnecessary. Shopping, checkout navigation and payment must work when any part of the analytics integration is unavailable.

This guide covers adapter version 1.0.0. The hosted receiver landed on staging at 1201ea3c5d2a. The hosted entry-event checks also require the paired API and checkout changes in #5870, 3bd509ed91d5. Before switching storefront GA4 to the adapter, use the merchant setup and qualification checklist to verify that your deployed API and checkout include those changes and that GET /api/v1/storefront/analytics-consent/configuration returns the expected configuration for your storefront. A store that has never switched receives replacementInForce: false and active: false. If the API cannot determine adoption, it returns replacementInForce: null and active: false. A merchant-policy handoff requires a current, active policy and its matching configuration revision. Without usable configuration, the adapter keeps GA4 off for a new visitor, drops their storefront events and can hide the analytics controls.

Install the reviewed package

Obtain litecommerce-storefront-consent-1.0.0.tgz through your platform installation handoff. Platform maintainers produce it with Node 24 and npm pack ./packages/storefront-consent from commit f66f24e28361b5282c103f6dea9b19e82470d04f. In your storefront, place the archive in vendor/ and check the bytes before installing.

openssl dgst -sha512 -binary vendor/litecommerce-storefront-consent-1.0.0.tgz | openssl base64 -A

The expected base64 digest is D64yWtuacrw/rUxehyRCi/sZ+Uz9RLygAWaqz2UzU6/+sbAl6UuiL7ENSKysi1TXzlMyGGiK2Sxca2itBn0bcQ==. If it matches, install the archive and commit it with the dependency declaration and lockfile.

npm install ./vendor/litecommerce-storefront-consent-1.0.0.tgz

Mount the first-party route

Mount this Fetch handler at POST /api/litecommerce/consent/v1 on the storefront. Resolve store from trusted server configuration for that installation. Its API key needs both storefront:read and storefront:consent. Supply the organization ID in tenant and the key's commerce environment (production or sandbox). Preview is a deployment environment. Omit trustedCountry if the hosting platform cannot establish the country of this specific request. Keep API keys, raw handles, capabilities, original references and request bodies out of client code, logs, traces and shared caches.

import { createConsentRoute } from "@litecommerce/storefront-consent/server";
 
// Server module. store and hosting come from your application.
export const consent = createConsentRoute({
  storefrontOrigin: store.verifiedHttpsOrigin,
  platformOrigin: store.platformApiOrigin,
  tenant: store.organizationId,
  environment: store.commerceEnvironment,
  apiKey: store.serverStorefrontKey,
  trustedCountry: request => hosting.countryForThisRequest(request),
  optOutPath: "/analytics-choices",
  async acceptMerchantPolicyHandoff(input) {
    const url = new URL("/api/v1/storefront/analytics-consent/checkout-handoff", store.platformApiOrigin);
    let retry = null;
    try {
      const response = await fetch(url, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "x-api-key": store.serverStorefrontKey,
          "x-storefront-origin": store.verifiedHttpsOrigin,
          "x-commerce-environment": store.commerceEnvironment,
        },
        body: JSON.stringify(input),
        cache: "no-store",
        credentials: "omit",
        redirect: "error",
        signal: AbortSignal.timeout(4000),
      });
      retry = response.headers.get("Retry-After");
      const data = response.ok ? await response.json() : null;
      return { status: response.status, data, retry };
    } catch {
      return { status: 503, data: null, retry };
    }
  },
});
 
export const POST = request => consent.POST(request);

Pass the incoming same-origin browser request to consent.POST and return its response, including each Set-Cookie header. The upstream handoff uses only the server headers in the example. Never forward the browser's Origin, cookies or claimed region to that receiver. If you supply server-rendered settings via await consent.render(request), serialize them with your framework's escaping and serve the page with Cache-Control: private, no-store. You can omit render data and let the adapter check on the first visible page.

Connect the prompt, privacy controls and GA4

Keep your existing consent-controlled GA4 loader in place until you qualify the target deployment.

Install once per eligible document. Include a mount point on those pages and link Analytics choices from the storefront's privacy controls to /analytics-choices on this exact origin. Mount the controls on that page too. The hosted receiver accepts only this HTTPS address with no query or fragment. Another adapter optOutPath produces a 400. Keep sensitive account, payment and other excluded pages free of analytics.

import { installStorefrontConsent, mountConsentControls } from "@litecommerce/storefront-consent/browser";
 
const adapter = installStorefrontConsent({
  controlPage: location.pathname === "/analytics-choices",
  tag: {
    start: id => analytics.loadApprovedGa4(id),
    event: (name, parameters) => analytics.sendApprovedEvent(name, parameters),
  },
});
const unmount = mountConsentControls(document.querySelector("#analytics-choices"), adapter, {
  privacyUrl: "/privacy",
});
cart.onViewItem(item => adapter.event("view_item", analytics.itemParameters(item)));

Provide the #analytics-choices element, your own published privacy URL and the application callbacks shown above. At the approved switch, move tag loading into start and route every application event, including SPA page views, through adapter.event when it occurs. Disable duplicate loaders and automatic page views outside this gate. Drop a suppressed event. On teardown call unmount() for the controls and adapter.dispose() when retiring the document integration.

The first eligible visit asks for a choice in opt-in mode. In regional opt-out mode a new visitor can instead see the merchant's notice when the current configuration and trusted country match and the required cookies work. A nonmatching or unknown country, an empty region list, or a missing previously known choice cannot establish that basis. An existing Decline keeps analytics off. The shopper can reopen Analytics choices and choose Allow later. Only a qualifying current lookup of that Allow can start GA4. Clicking, receiving a successful save, or receiving a message from another tab does not by itself open the gate.

Decline stops the storefront's application events immediately. A tagged page disables the tag and attempts replacement. Show the adapter's saving, saved or could not confirm result for the storefront choice. Each prepared checkout has its own result in the controls. A durable storefront save and a checkout withdrawal can succeed or fail independently. After complete site-data erasure, in a private window or in another browser, a shopper can appear new and may need to opt out again in a selected region. A withdrawal already accepted for an addressed checkout still applies to that checkout.

Prepare a new checkout

Use the server handler that issues a genuinely new original checkout. Add the custody cookie to that same commerce response. Include only the non-authorizing descriptor alongside the normal commerce result. The server must know from creation and adoption whether this is first issuance under the replacement. Omit preparation on replay, resume or uncertain issuance.

// In the checkout creation handler, using the consent object from the server module.
const responseHeaders = new Headers(creation.responseHeaders);
let consentPreparation = null;
try {
  consentPreparation = consent.prepareNewCheckout(responseHeaders, {
    kind: "new-original",
    firstIssuance: creation.isVerifiedFirstIssuance,
    replacementInForce: adoption.replacementInForce === true,
    originalReference: creation.originalCheckoutReference,
  });
} catch {
  // Checkout still works when the analytics preparation is unavailable.
}
return Response.json({ ...creation.publicReply, consentPreparation }, {
  status: creation.status,
  headers: responseHeaders,
});

Use your commerce handler's existing response headers and status when adding preparation. On the storefront, start the analytics handoff when the descriptor and adapter are ready. Mark departures synchronously on both link and programmatic navigation paths. Leave the checkout URL free of consent data and allow navigation even if the handoff has no answer.

if (creation.consentPreparation) {
  void adapter.ready.then(() => adapter.handoff(creation.consentPreparation));
}
checkoutLink.addEventListener("click", () => adapter.markCheckoutDeparture());
function goToCheckout(url) {
  adapter.markCheckoutDeparture();
  location.assign(url);
}

The adapter checks custody, journals the original operation and rechecks the current choice or configuration before sending. Re-entry cannot mint a replacement capability. With matching custody and a usable journal, a later eligible page can continue an addressed withdrawal. Five automatic attempts per pass include refusals, up to two reads, one exact resend and one resumption after a 429. Honor the pause. An eligible press of Retry checkout withdrawal can send one pending exact write separately. A missing handoff receipt can require an addressed read followed by initial Deny or an update at the reported revision. The original preparation deadline is 72 hours, subject to an earlier end of authority. Lost custody leaves the result unconfirmed. Denied when last read describes a read. Only a matching accepted write confirms delivery of the withdrawal for that checkout.

What hosted checkout can measure

BasisEvidence at checkoutEligible events
Shopper AllowA current, usable grant for this original. The server and the first page read must agree on the grant, configuration and unexpired cutoff to count entry.Sanitized page_view on entry, begin_checkout at first payable render, and purchase on confirmed order, each with permission at occurrence and send.
Regional merchant policyAn accepted policy handoff with shopper state unknown, usable update authority and no known Decline. Hosted checkout checks the trusted country and storefront eligibility on navigation and again on the first permit request. The acknowledged permit must match the navigation, including the checkout consent revision.Sanitized page_view and begin_checkout can count even if the shopper leaves before paying. A purchase needs payable and confirmed observations under uninterrupted permission.

In regional opt-out mode, the qualifying checkout shows Analytics choices on its first view. The link opens the verified storefront controls in a new tab. Seeing the link does not establish that an event was sent.

For either basis, checkout must confirm entry permission less than 30 seconds after navigation starts, including loading time and any sleep the browser clocks record. The page must stay visible and focused from the time its activity recorder first runs. Missing activity evidence, a missed deadline or a failed or mismatched first check omits both entry events. A later check cannot backfill them. Checkout evaluates a confirmed purchase separately.

The merchant-policy receiver is server-only. Forward the twelve fields supplied by the adapter unchanged. They include version: 1, basis: "merchant_policy", shopperState: "unknown" and assertedAt: null. First acceptance returns 201 with state unknown, revision 1 and generation 0. An exact replay writes nothing and can return a later granted or denied state. Hosted checkout independently verifies eligibility on its own request. A changed verified storefront domain invalidates the earlier basis, even with the same measurement ID. Sandbox commerce never qualifies for the hosted merchant-policy basis.

A malformed handoff or wrong opt-out path returns 400. Key or origin failures return 401/403. A neutral 404 covers unavailable references, 409 covers a conflict, 429 carries backoff and If the service returns 503, continue commerce with hosted measurement unavailable. For both bases a received Decline stops new use. Accepted addressed withdrawal owes cleanup on the original, including a recognized return after commerce expiry while that original remains addressable. Cleanup can only attempt owned cookies reachable in that browser and domain. It cannot recall data Google already received.

Implementing a headless client

The maintained package is optional. A custom first-party server can use the same versioned operations under /api/v1/storefront/analytics-consent with a scoped key and verified x-storefront-origin. Use the OpenAPI schemas for the exact bodies.

OperationUse
GET /configurationRead active configuration, its revision, mode, return-check setting and the region result for this request with storefront:read.
POST /resolvePresent all scoped handles. Optionally establish an empty binding or carry pending Declines. This can merge records or save a Decline.
POST /saveSend the handles and exact named Allow or Decline command with the genuine click time. Match the returned outcome to the command. Resolve/save require storefront:consent. A key with both scopes can receive configuration in the same call when available.
POST /checkout-handoffSubmit the server-only merchant-policy handoff with storefront:consent. A recorded handoff grants no shopper permission.

For shopper handoffs, addressed updates, private reads and cleanup, use the checkout-scoped API and retry examples. A headless client owns first-party cookie custody, capture-before-send, bounded recovery, event gating, genuine newer-choice checks and honest shopper feedback. A headless server that cannot establish those facts must leave the affected permission or withdrawal unconfirmed.