Skip to content

Commit 3c69aae

Browse files
authored
fix: preserve visitor-specific loaders and pixel commands (#937)
1 parent b0419ed commit 3c69aae

27 files changed

Lines changed: 479 additions & 139 deletions

‎FIRST_PARTY.md‎

Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,19 +2,26 @@
22

33
## Architecture
44

5-
Two distinct mechanisms for first-party routing:
5+
First-party routing uses bundling or SDK endpoint configuration.
66

77
### Path A: Bundle + Rewrite + Intercept (most scripts)
88
1. **Build**: Downloads script, rewrites hardcoded URLs via AST using domain-to-proxy mappings derived from `proxy-configs.ts` `domains[]`, applies SDK-specific `postProcess` patches
99
2. **Client**: Intercept plugin wraps `fetch`/`sendBeacon`/`XHR`/`Image.src` via `__nuxtScripts` — any non-same-origin URL is automatically proxied through `/_scripts/p/<host><path>`
1010
3. **Server**: Nitro handler at `/_scripts/p/**` extracts the domain from the path, reconstructs the upstream URL, and proxies with privacy transforms
1111

12-
### Path B: Config Injection + Proxy (PostHog only)
12+
### Path B: Config Injection + Proxy
1313
1. **Build**: `autoInject` on the PostHog proxy config sets `apiHost` → `/_scripts/p/us.i.posthog.com`
1414
2. **Client**: SDK natively uses the injected endpoint — no interception needed
1515
3. **Server**: Same Nitro proxy handler
1616

17-
PostHog is the only true Path B script — it uses npm mode (`src: false`, no script to download/rewrite).
17+
PostHog uses npm mode, with no loader to download or rewrite.
18+
Google Analytics keeps its visitor-specific loader remote.
19+
The module provides a collection endpoint for its initial `gtag` configuration through `transport_url`.
20+
Per-script `proxy: false` and static output disable that endpoint.
21+
22+
TikTok Pixel keeps its loader and collection requests direct to preserve visitor IDs and vendor cookies.
23+
It has no collection proxy or proxy anonymization.
24+
Google Tag Manager also keeps its visitor-specific loader remote and has no collection proxy.
1825

1926
### How runtime interception works
2027
The AST rewriter transforms API calls in downloaded third-party scripts:
@@ -51,7 +58,7 @@ Some SDKs have quirks that require targeted regex patches after AST rewriting. T
5158
- **Rybbit**: SDK derives API host from `document.currentScript.src.split("/script.js")[0]` — breaks when bundled to `/_scripts/assets/<hash>.js`. Regex replaces the split expression with the proxy path.
5259
- **Fathom**: SDK checks `src.indexOf("cdn.usefathom.com") < 0` to detect self-hosted mode and overrides the tracker URL. Regex neutralizes this check.
5360

54-
Note: Google Analytics previously needed `postProcess` regex patches for dynamically constructed collect URLs. This is no longer needed since the runtime intercept plugin catches all non-same-origin URLs at the `sendBeacon`/`fetch` call site.
61+
Google Analytics uses its configured collection endpoint instead of AST rewriting or native network interception.
5562

5663
## Path aliases (`proxy.alias`)
5764

@@ -127,19 +134,20 @@ Four presets in `proxy-configs.ts` cover all proxy-enabled scripts:
127134
| Preset | Flags | Used by |
128135
|---|---|---|
129136
| `PRIVACY_NONE` | all false | (not currently assigned to any script) |
130-
| `PRIVACY_FULL` | all true | Meta, TikTok, X, Snap, Reddit, LinkedIn |
137+
| `PRIVACY_FULL` | all true | Meta, X, Snap, Reddit, LinkedIn |
131138
| `PRIVACY_HEATMAP` | ip, language, hardware | GA, Clarity, Hotjar |
132139
| `PRIVACY_IP_ONLY` | ip only | PostHog, Plausible, Umami, Rybbit, Databuddy, Ahrefs, Fathom, CF Web Analytics, Vercel, Matomo, Carbon Ads, Lemon Squeezy, Intercom, Gravatar, YouTube, Vimeo, Calendly |
133140

134-
Note: GTM, Segment, Crisp, Mixpanel, Bing UET, SpeedCurve, Pulse, and Statable have no proxy capability, so no privacy transforms are applied.
141+
Note: TikTok, GTM, Segment, Crisp, Mixpanel, Bing UET, SpeedCurve, Pulse, and Statable have no proxy capability, so no privacy transforms are applied.
135142

136143
## Script Support
137144

138145
| Config Key | Registry Scripts | Privacy | Mechanism |
139146
|---|---|---|---|
140-
| `googleAnalytics` | googleAnalytics, **googleAdsense** | `PRIVACY_HEATMAP` | Path A |
147+
| `googleAnalytics` | googleAnalytics | `PRIVACY_HEATMAP` | Path B, remote loader |
148+
| `googleAdsense` | googleAdsense | `PRIVACY_HEATMAP` | Path A, shared GA proxy config |
141149
| `metaPixel` | metaPixel | `PRIVACY_FULL` | Path A |
142-
| `tiktokPixel` | tiktokPixel | `PRIVACY_FULL` | Path A |
150+
| `tiktokPixel` | tiktokPixel | n/a | Direct loader and collection |
143151
| `xPixel` | xPixel | `PRIVACY_FULL` | Path A |
144152
| `snapchatPixel` | snapchatPixel | `PRIVACY_FULL` | Path A |
145153
| `redditPixel` | redditPixel | `PRIVACY_FULL` | Path A |
@@ -163,7 +171,7 @@ Note: GTM, Segment, Crisp, Mixpanel, Bing UET, SpeedCurve, Pulse, and Statable h
163171
| `intercom` | intercom | `PRIVACY_IP_ONLY` | Path A |
164172
| `gravatar` | gravatar | `PRIVACY_IP_ONLY` | Path A |
165173
| `calendly` | calendly | `PRIVACY_IP_ONLY` | Path A |
166-
| `googleTagManager` | googleTagManager | n/a | Bundle only |
174+
| `googleTagManager` | googleTagManager | n/a | Direct loader and runtime scripts |
167175
| `segment` | segment | n/a | Bundle only |
168176
| `crisp` | crisp | n/a | Bundle only |
169177
| `speedcurve` | speedcurve | n/a | No proxy (ID-parameterized CDN URL) |
@@ -182,8 +190,10 @@ Note: GTM, Segment, Crisp, Mixpanel, Bing UET, SpeedCurve, Pulse, and Statable h
182190
### Domain-based proxy routing
183191
Each proxy config declares `domains[]` — the list of third-party domains that script communicates with. The transform plugin derives rewrite rules at build time as `{ from: domain, to: proxyPrefix/domain }`. The server handler extracts the domain from the proxy path and forwards to the upstream.
184192

185-
### Runtime intercept: no rules needed
186-
The intercept plugin proxies any non-same-origin URL. No domain allowlist or rule matching is required because `__nuxtScripts` wrappers are only injected into AST-rewritten third-party scripts. Regular app code uses native `fetch`/`sendBeacon` and is unaffected.
193+
### Runtime interception
194+
Bundled SDKs call `__nuxtScripts` wrappers after AST rewriting.
195+
Google Analytics uses its configured collection endpoint.
196+
Native application requests retain their original URLs.
187197

188198
The server handler extracts the target domain directly from the proxy path (`/_scripts/p/<host>/<path>`) and looks up privacy config by domain. Unrecognized domains default to full anonymization (fail-closed).
189199

‎docs/content/docs/1.guides/2.first-party.md‎

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -30,10 +30,11 @@ The initial request no longer reaches the original host or pays its [DNS and con
3030

3131
### Reverse Proxy
3232

33-
Runtime requests (analytics beacons, pixel fires, tracking calls) are intercepted and forwarded through Nitro server routes at `/_scripts/p/`. The module rewrites URLs at two levels:
33+
Runtime requests (analytics beacons, pixel fires, tracking calls) are intercepted and forwarded through Nitro server routes at `/_scripts/p/`. The module routes requests through source rewriting, runtime wrappers, or SDK endpoint configuration:
3434

3535
1. **AST rewriting** at build time: third-party domains in the bundled script source are replaced with your proxy path
36-
2. **Runtime wrappers** on the client: the AST transform redirects `fetch`, `sendBeacon`, `XMLHttpRequest`, and `Image` calls in supported bundled SDKs through Nuxt Scripts wrappers, which proxy dynamically constructed URLs
36+
2. **Runtime wrappers** on the client: bundled SDKs use Nuxt Scripts wrappers for dynamically constructed URLs.
37+
3. **SDK endpoint configuration**: Google Analytics and PostHog receive a collection endpoint on your server. Their SDKs send events there without source rewriting.
3738

3839
Supported script and collection requests use same-origin URLs, so cookies set on those responses are not [third-party cookies](https://developer.mozilla.org/en-US/docs/Web/Privacy/Guides/Third-party_cookies). Host-based blocking rules are less likely to match them, although path-based or behavioral rules can still block requests.
3940

@@ -74,7 +75,7 @@ Each proxied script has a default privacy tier chosen around the data its SDK ne
7475

7576
| Tier | What's anonymized | Scripts |
7677
|------|-------------------|---------|
77-
| **Full** | IP, user agent, language, screen, timezone, hardware fingerprints | Meta Pixel, TikTok Pixel, X Pixel, Snapchat Pixel, Reddit Pixel, LinkedIn Insight Tag |
78+
| **Full** | IP, user agent, language, screen, timezone, hardware fingerprints | Meta Pixel, X Pixel, Snapchat Pixel, Reddit Pixel, LinkedIn Insight Tag |
7879
| **Heatmap-safe** | IP, language, hardware fingerprints (preserves screen and user agent for session replay) | Google Analytics, Google AdSense, Microsoft Clarity, Hotjar |
7980
| **IP only** | IP addresses anonymized to subnet level | Plausible, PostHog, Umami, Cloudflare Web Analytics, Vercel Analytics, Rybbit, Databuddy, Matomo, Ahrefs Web Analytics, Intercom, YouTube, Vimeo, Gravatar, Calendly |
8081

@@ -224,14 +225,14 @@ export default defineNuxtConfig({
224225
scripts: {
225226
registry: {
226227
// Disables bundling and the proxy rewrites that depend on it
227-
googleAnalytics: { id: 'G-XXXXXX', bundle: false },
228+
metaPixel: { id: '123456', bundle: false },
228229
}
229230
}
230231
})
231232
```
232233

233234
::callout{type="info"}
234-
PostHog receives the proxy endpoint through SDK config, so it can proxy collection requests without bundling. Matomo does not: its normal main-thread loader remains direct unless you use the separate Partytown routing path described below.
235+
PostHog receives its proxy endpoint through SDK config. Google Analytics receives its collection endpoint through SDK configuration. Both can proxy without bundling. Matomo does not: its normal main-thread loader remains direct unless you use the separate Partytown routing path described below.
235236
::
236237

237238
### Static Hosting (SSG)
@@ -264,26 +265,28 @@ These scripts are downloaded at build time, served from your domain, and have th
264265

265266
| Category | Scripts |
266267
|----------|---------|
267-
| **Analytics** | [Google Analytics](/scripts/google-analytics), [Plausible](/scripts/plausible-analytics), [Cloudflare Web Analytics](/scripts/cloudflare-web-analytics), [Umami](/scripts/umami-analytics), [Rybbit](/scripts/rybbit-analytics), [Databuddy](/scripts/databuddy-analytics), [Ahrefs Web Analytics](/scripts/ahrefs-analytics), [Vercel Analytics](/scripts/vercel-analytics), [Microsoft Clarity](/scripts/clarity), [Hotjar](/scripts/hotjar) |
268-
| **Ad Pixels** | [Meta Pixel](/scripts/meta-pixel), [TikTok Pixel](/scripts/tiktok-pixel), [X Pixel](/scripts/x-pixel), [Snapchat Pixel](/scripts/snapchat-pixel), [Reddit Pixel](/scripts/reddit-pixel), [LinkedIn Insight Tag](/scripts/linkedin-insight), [Google AdSense](/scripts/google-adsense) |
268+
| **Analytics** | [Plausible](/scripts/plausible-analytics), [Cloudflare Web Analytics](/scripts/cloudflare-web-analytics), [Umami](/scripts/umami-analytics), [Rybbit](/scripts/rybbit-analytics), [Databuddy](/scripts/databuddy-analytics), [Ahrefs Web Analytics](/scripts/ahrefs-analytics), [Vercel Analytics](/scripts/vercel-analytics), [Microsoft Clarity](/scripts/clarity), [Hotjar](/scripts/hotjar) |
269+
| **Ad Pixels** | [Meta Pixel](/scripts/meta-pixel), [X Pixel](/scripts/x-pixel), [Snapchat Pixel](/scripts/snapchat-pixel), [Reddit Pixel](/scripts/reddit-pixel), [LinkedIn Insight Tag](/scripts/linkedin-insight), [Google AdSense](/scripts/google-adsense) |
269270
| **Video** | [Vimeo Player](/scripts/vimeo-player) |
270271
| **Utility** | [Intercom](/scripts/intercom), [Gravatar](/scripts/gravatar) |
271272

272-
### Proxy Only (Package-backed)
273+
### Proxy Only
273274

274-
The module doesn't bundle PostHog's SDK because it comes from a package dependency, but it can still send collection requests through your server:
275+
These integrations keep their SDK outside the build bundle and can send collection requests through your server:
275276

276277
| Script | How it works |
277278
|--------|-------------|
279+
| [Google Analytics](/scripts/google-analytics) | Visitor-specific loader stays remote. Collection requests use the proxy on the main thread and with Partytown. |
278280
| [PostHog](/scripts/posthog) | SDK installed as [`posthog-js`](https://posthog.com/docs/libraries/js#option-2-install-via-package-manager). Proxy endpoint auto-injected via `apiHost` config. |
279281

282+
Google still receives direct loader and other SDK requests from the browser. Proxy privacy transforms apply only to collection requests.
283+
280284
### Bundled, with Third-Party Runtime Traffic
281285

282286
These integrations serve their main loader from your domain, but some runtime requests still go directly to third-party servers:
283287

284288
| Script | Remaining direct traffic |
285289
|--------|--------------------------|
286-
| [Google Tag Manager](/scripts/google-tag-manager) | GTM's core function is loading other scripts at runtime. Those runtime scripts bypass build-time rewriting. |
287290
| [Fathom](/scripts/fathom-analytics) | Fathom's bot detection rejects beacons from the server's IP, so Nuxt Scripts bundles the SDK but leaves beacons direct. |
288291
| [Pulse](/scripts/pulse-analytics) | Pulse identifies visitors from the connecting IP, so proxied beacons would merge everyone into one visitor. Nuxt Scripts bundles the tracker but leaves beacons direct. |
289292
| [Statable](/scripts/statable-analytics) | Statable identifies visitors from the connecting IP and user agent, so proxied beacons would merge everyone into one visitor. Nuxt Scripts bundles the tracker but leaves beacons direct. |
@@ -303,6 +306,8 @@ These integrations load their SDKs and runtime traffic directly from their confi
303306

304307
| Script | Direct-loading behavior |
305308
|--------|-------------------------|
309+
| [TikTok Pixel](/scripts/tiktok-pixel) | Loader and collection requests stay direct to preserve visitor IDs and vendor cookies. Proxy anonymization does not apply. |
310+
| [Google Tag Manager](/scripts/google-tag-manager) | Visitor-specific loader and scripts it loads remain direct. |
306311
| **Stripe** | [Stripe requires Stripe.js to load directly from `js.stripe.com`](https://docs.stripe.com/payments/finalize-payments-on-the-server?platform=web&type=setup) for PCI compliance. |
307312
| **PayPal** | Nuxt Scripts loads PayPal's v6 core from PayPal's documented [`/web-sdk/v6/core` URL](https://developer.paypal.com/upgrade/ec/guide/Web%20SDK%20v6/); the registry declares no bundle or collection proxy. |
308313
| **Google reCAPTCHA** | Nuxt Scripts loads `api.js` or `enterprise.js` directly from Google, or from `recaptcha.net`; the registry declares no bundle or collection proxy. Google separately recommends loading reCAPTCHA early because [more page context improves its assessment](https://developers.google.com/recaptcha/docs/loading). |

‎docs/content/scripts/tiktok-pixel.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,10 @@ Use [`useScriptTikTokPixel()`{lang="ts"}](/scripts/tiktok-pixel){lang="ts"} to l
1818
::script-docs
1919
::
2020

21+
The loader and collection requests go directly to TikTok to preserve visitor IDs and [vendor cookies](https://ads.tiktok.com/resources/help/article/using-cookies-with-tiktok-pixel?lang=en).
22+
Nuxt Scripts does not bundle TikTok Pixel or apply collection proxying and IP anonymization.
23+
Use a [consent trigger](/docs/guides/consent#binary-load-gate) to control when requests start.
24+
2125
## Disabling automatic page views
2226

2327
By default, TikTok Pixel tracks a page view during initialization. Disable it in the composable call:

‎packages/script/src/module.ts‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,7 @@ export function isProxyDisabled(
123123
return true
124124
if (runtimeConfig) {
125125
const rtEntry = (runtimeConfig.public?.scripts as Record<string, any> | undefined)?.[registryKey]
126-
if (rtEntry?.proxy === false)
126+
if (rtEntry?.proxy === false || rtEntry?.scriptOptions?.proxy === false)
127127
return true
128128
}
129129
return false
@@ -807,7 +807,7 @@ export default defineNuxtModule<ModuleOptions>({
807807
}
808808
if (!script.proxy)
809809
continue
810-
if (isProxyDisabled(key, config.registry))
810+
if (isProxyDisabled(key, config.registry, nuxt.options.runtimeConfig))
811811
continue
812812

813813
const configKey = (typeof script.proxy === 'string' ? script.proxy : key) as RegistryScriptKey
@@ -875,6 +875,12 @@ export default defineNuxtModule<ModuleOptions>({
875875
aliasOwner.set(alias, domain)
876876
}
877877
const aliasToDomain = invertAliasMap(domainAliases)
878+
if (proxyConfiguredKeys.includes('googleAnalytics') && !isProxyDisabled('googleAnalytics', config.registry, nuxt.options.runtimeConfig)) {
879+
nuxt.options.runtimeConfig.public['nuxt-scripts'] = defu(
880+
{ proxyEndpoints: { googleAnalytics: aliasProxyValue(`${proxyPrefix}/www.google-analytics.com`, proxyPrefix, proxyAlias) } },
881+
nuxt.options.runtimeConfig.public['nuxt-scripts'] as any,
882+
) as any
883+
}
878884

879885
// Register intercept plugin
880886
addPluginTemplate({
@@ -905,7 +911,7 @@ export default defineNuxtModule<ModuleOptions>({
905911
if (partytownScripts.size && hasNuxtModule('@nuxtjs/partytown')) {
906912
const partytownConfig = (nuxt.options as any).partytown || {}
907913
if (!partytownConfig.resolveUrl) {
908-
partytownConfig.resolveUrl = generatePartytownResolveUrl(proxyPrefix, domainAliases)
914+
partytownConfig.resolveUrl = generatePartytownResolveUrl(proxyPrefix, domainAliases, Object.keys(domainPrivacy))
909915
;(nuxt.options as any).partytown = partytownConfig
910916
logger.info('[partytown] Auto-configured resolveUrl for proxy')
911917
}

‎packages/script/src/plugins/transform.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -317,8 +317,8 @@ export function NuxtScriptBundleTransformer(options: AssetBundlerTransformerOpti
317317
else {
318318
// find the registry node
319319
const registryNode = options.scripts?.find(i => i.import.name === fnName)
320-
if (!registryNode) {
321-
// silent failure
320+
if (!registryNode || !registryNode.bundle) {
321+
// Registry capabilities are a ceiling, including explicit bundle overrides.
322322
return
323323
}
324324
// The composable name may diverge from the registry key (e.g.

0 commit comments

Comments
 (0)