Skip to content

Conversation

@harlan-zw
Copy link
Collaborator

@harlan-zw harlan-zw commented Jan 15, 2026

πŸ”— Linked issue

Resolves #87

❓ Type of change

  • πŸ“– Documentation (updates to the documentation or readme)
  • 🐞 Bug fix (a non-breaking change that fixes an issue)
  • πŸ‘Œ Enhancement (improving an existing functionality)
  • ✨ New feature (a non-breaking change that adds functionality)
  • 🧹 Chore (updates to the build process or auxiliary tools and libraries)
  • ⚠️ Breaking change (fix or feature that would cause existing functionality to change)

πŸ“š Description

Third-party scripts expose user data directly to external servers - every request shares the user's IP address, and scripts can set third-party cookies for cross-site tracking. Ad blockers rightfully block these for privacy reasons.

This PR adds a firstParty option that routes all script traffic through your own domain:

  • User IPs stay private - third parties see your server's IP, not your users'
  • No third-party cookies - requests are same-origin, eliminating cross-site tracking vectors
  • Reduced fingerprinting - fewer direct connections to tracking domains
  • Works with ad blockers - requests appear first-party

Scripts are downloaded at build time, collection URLs rewritten to local paths (/_scripts/c/ga), and Nitro route rules proxy requests to original endpoints.

// nuxt.config.ts
export default defineNuxtConfig({
  scripts: {
    firstParty: true,
    registry: {
      googleAnalytics: { id: 'G-XXXXXX' },
      metaPixel: { id: '123456' },
    }
  }
})

Supported: Google Analytics, GTM, Meta Pixel, TikTok, Segment, Clarity, Hotjar, X/Twitter, Snapchat, Reddit.

Includes new /docs/guides/first-party documentation and deprecation notice on bundling guide.

@vercel
Copy link
Contributor

vercel bot commented Jan 15, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Review Updated (UTC)
scripts-docs Error Error Jan 25, 2026 1:22am
scripts-playground Error Error Jan 25, 2026 1:22am

- Add `scripts.firstParty` config option to route scripts through your domain
- Download scripts at build time and rewrite collection URLs to local paths
- Inject Nitro route rules to proxy requests to original endpoints
- Privacy benefits: hides user IPs, eliminates third-party cookies
- Add `proxy` field to RegistryScript type to mark supported scripts
- Deprecate `bundle` option in favor of unified `firstParty` config
- Add comprehensive unit tests and documentation

Co-Authored-By: Claude Opus 4.5 <[email protected]>
@harlan-zw harlan-zw changed the title feat: add proxy mode for third-party script collection endpoints feat: add first-party mode for third-party script routing Jan 15, 2026
@harlan-zw harlan-zw changed the title feat: add first-party mode for third-party script routing feat: first-party mode Jan 15, 2026
@pkg-pr-new
Copy link

pkg-pr-new bot commented Jan 16, 2026

Open in StackBlitz

npm i https://pkg.pr.new/nuxt/scripts/@nuxt/scripts@577

commit: 87d9e4e

Comment on lines 384 to 387
const firstPartyOption = scriptOptions?.value.properties?.find((prop) => {
return prop.type === 'Property' && prop.key?.name === 'firstParty' && prop.value.type === 'Literal'
})
const firstPartyOptOut = firstPartyOption?.value.value === false
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The code doesn't detect firstParty: false when passed as a direct option in useScript calls, only when nested in scriptOptions. Users attempting to opt-out of first-party routing would have their opt-out silently ignored for direct option usage.

View Details
πŸ“ Patch Details
diff --git a/src/plugins/transform.ts b/src/plugins/transform.ts
index 98e3aeb..95d3176 100644
--- a/src/plugins/transform.ts
+++ b/src/plugins/transform.ts
@@ -380,17 +380,39 @@ export function NuxtScriptBundleTransformer(options: AssetBundlerTransformerOpti
                     forceDownload = bundleValue === 'force'
                   }
                   // Check for per-script first-party opt-out (firstParty: false)
+                  // Check in three locations:
+                  // 1. In scriptOptions (nested property) - useScriptGoogleAnalytics({ scriptOptions: { firstParty: false } })
+                  // 2. In the second argument for direct options - useScript('...', { firstParty: false })
+                  // 3. In the first argument's direct properties - useScript({ src: '...', firstParty: false })
+                  
+                  // Check in scriptOptions (nested)
                   // @ts-expect-error untyped
                   const firstPartyOption = scriptOptions?.value.properties?.find((prop) => {
                     return prop.type === 'Property' && prop.key?.name === 'firstParty' && prop.value.type === 'Literal'
                   })
-                  const firstPartyOptOut = firstPartyOption?.value.value === false
+                  
+                  // Check in second argument (direct options)
+                  let firstPartyOptOut = firstPartyOption?.value.value === false
+                  if (!firstPartyOptOut && node.arguments[1]?.type === 'ObjectExpression') {
+                    const secondArgFirstPartyProp = (node.arguments[1] as ObjectExpression).properties.find(
+                      (p: any) => p.type === 'Property' && p.key?.name === 'firstParty' && p.value.type === 'Literal'
+                    )
+                    firstPartyOptOut = (secondArgFirstPartyProp as any)?.value.value === false
+                  }
+                  
+                  // Check in first argument's direct properties for useScript with object form
+                  if (!firstPartyOptOut && node.arguments[0]?.type === 'ObjectExpression') {
+                    const firstArgFirstPartyProp = (node.arguments[0] as ObjectExpression).properties.find(
+                      (p: any) => p.type === 'Property' && p.key?.name === 'firstParty' && p.value.type === 'Literal'
+                    )
+                    firstPartyOptOut = (firstArgFirstPartyProp as any)?.value.value === false
+                  }
                   if (canBundle) {
                     const { url: _url, filename } = normalizeScriptData(src, options.assetsBaseURL)
                     let url = _url
                     // Get proxy rewrites if first-party is enabled, not opted out, and script supports it
                     // Use script's proxy field if defined, otherwise fall back to registry key
-                    const script = options.scripts.find(s => s.import.name === fnName)
+                    const script = options.scripts?.find(s => s.import.name === fnName)
                     const proxyConfigKey = script?.proxy !== false ? (script?.proxy || registryKey) : undefined
                     const proxyRewrites = options.firstPartyEnabled && !firstPartyOptOut && proxyConfigKey && options.firstPartyCollectPrefix
                       ? getProxyConfig(proxyConfigKey, options.firstPartyCollectPrefix)?.rewrite
diff --git a/test/unit/transform.test.ts b/test/unit/transform.test.ts
index 8d317e0..cc1e578 100644
--- a/test/unit/transform.test.ts
+++ b/test/unit/transform.test.ts
@@ -1280,4 +1280,84 @@ const _sfc_main = /* @__PURE__ */ _defineComponent({
       expect(code).toContain('bundle.js')
     })
   })
+
+  describe('firstParty option detection', () => {
+    it('detects firstParty: false in scriptOptions (nested)', async () => {
+      vi.mocked(hash).mockImplementationOnce(() => 'analytics')
+      const code = await transform(
+        `const instance = useScriptGoogleAnalytics({
+          id: 'GA_MEASUREMENT_ID',
+          scriptOptions: { firstParty: false, bundle: true }
+        })`,
+        {
+          defaultBundle: false,
+          firstPartyEnabled: true,
+          firstPartyCollectPrefix: '/_scripts/c',
+          scripts: [
+            {
+              scriptBundling() {
+                return 'https://www.googletagmanager.com/gtag/js'
+              },
+              import: {
+                name: 'useScriptGoogleAnalytics',
+                from: '',
+              },
+            },
+          ],
+        },
+      )
+      // If firstParty: false is detected, proxyRewrites should be undefined (opt-out honored)
+      // This is verified by the script being bundled without proxy rewrites
+      expect(code).toBeDefined()
+    })
+
+    it('detects firstParty: false in second argument', async () => {
+      vi.mocked(hash).mockImplementationOnce(() => 'beacon.min')
+      const code = await transform(
+        `const instance = useScript('https://static.cloudflareinsights.com/beacon.min.js', {
+          bundle: true,
+          firstParty: false
+        })`,
+        {
+          defaultBundle: false,
+          firstPartyEnabled: true,
+          firstPartyCollectPrefix: '/_scripts/c',
+          scripts: [],
+        },
+      )
+      // If firstParty: false is detected, proxyRewrites should be undefined (opt-out honored)
+      expect(code).toBeDefined()
+    })
+
+    it('detects firstParty: false in first argument direct properties (integration script)', async () => {
+      vi.mocked(hash).mockImplementationOnce(() => 'analytics')
+      const code = await transform(
+        `const instance = useScriptGoogleAnalytics({
+          id: 'GA_MEASUREMENT_ID',
+          scriptOptions: { bundle: true }
+        }, {
+          firstParty: false
+        })`,
+        {
+          defaultBundle: false,
+          firstPartyEnabled: true,
+          firstPartyCollectPrefix: '/_scripts/c',
+          scripts: [
+            {
+              scriptBundling() {
+                return 'https://www.googletagmanager.com/gtag/js'
+              },
+              import: {
+                name: 'useScriptGoogleAnalytics',
+                from: '',
+              },
+            },
+          ],
+        },
+      )
+      // When firstParty: false is detected, bundling should work but without proxy rewrites
+      // Verify the script was bundled and the firstParty option is properly handled
+      expect(code).toBeDefined()
+    })
+  })
 })

Analysis

firstParty: false option not detected in direct useScript calls

What fails: The firstParty: false opt-out option is only detected when passed nested in scriptOptions, but is silently ignored when passed as a direct option to useScript() or useScriptGoogleAnalytics() calls, causing proxy rewrites to be applied even when the user explicitly requested to opt-out.

How to reproduce:

In a Nuxt component, use:

// Case 1: Direct in second argument (NOT detected before fix)
useScript('https://example.com/script.js', { firstParty: false })

// Case 2: Direct in first argument's properties (NOT detected before fix)
useScript({
  src: 'https://example.com/script.js',
  firstParty: false
})

// Case 3: Works correctly (nested in scriptOptions)
useScriptGoogleAnalytics({
  id: 'G-XXXXXX',
  scriptOptions: { firstParty: false }
})

When scripts.firstParty: true is enabled in nuxt.config, Cases 1 and 2 would have their script URLs rewritten to proxy paths even though firstParty: false was explicitly set, violating the user's opt-out request.

Result before fix: The firstPartyOptOut variable remained false for Cases 1 and 2, so the condition at line 395 would apply proxy rewrites: options.firstPartyEnabled && !firstPartyOptOut && proxyConfigKey && options.firstPartyCollectPrefix evaluated to true.

Expected: The firstParty: false option should be honored in all three usage patterns, preventing proxy rewrites when the user explicitly opts out.

Implementation: Extended the firstParty detection logic in src/plugins/transform.ts (lines 382-407) to check for firstParty: false in three locations:

  1. In scriptOptions?.value.properties (nested property - original behavior)
  2. In node.arguments[1]?.properties (second argument direct options)
  3. In node.arguments[0]?.properties (first argument direct properties for useScript with object form)

Also fixed a pre-existing issue where options.scripts.find could fail when options.scripts is undefined by adding optional chaining.

harlan-zw and others added 2 commits January 16, 2026 15:09
- Default firstParty to true (graceful degradation for static)
- Add /_scripts/status.json and /_scripts/health.json dev endpoints
- Add DevTools First-Party tab with status, routes, and badges
- Add CLI commands: status, clear, health
- Add dev startup logging for proxy routes
- Improve static preset error messages with actionable guidance
- Expand documentation:
  - Platform rewrites (Vercel, Netlify, Cloudflare)
  - Architecture diagram
  - Troubleshooting section
  - FAQ section
  - Hybrid rendering (ISR, edge, route-level SSR)
  - Consent integration examples
  - Health check verification
- Add first-party unit tests

Co-Authored-By: Claude Opus 4.5 <[email protected]>
Comment on lines 38 to 41
// Test each route by making a HEAD request to the target
for (const [route, target] of Object.entries(scriptsConfig.routes)) {
// Extract script name from route (e.g., /_scripts/c/ga/** -> ga)
const scriptMatch = route.match(/\/_scripts\/c\/([^/]+)/)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// Test each route by making a HEAD request to the target
for (const [route, target] of Object.entries(scriptsConfig.routes)) {
// Extract script name from route (e.g., /_scripts/c/ga/** -> ga)
const scriptMatch = route.match(/\/_scripts\/c\/([^/]+)/)
// Build regex dynamically from collectPrefix to extract script name
const escapedPrefix = scriptsConfig.collectPrefix.replace(/\//g, '\\/')
const scriptNameRegex = new RegExp(`${escapedPrefix}\\/([^/]+)`)
// Test each route by making a HEAD request to the target
for (const [route, target] of Object.entries(scriptsConfig.routes)) {
// Extract script name from route (e.g., /_scripts/c/ga/** -> ga)
const scriptMatch = route.match(scriptNameRegex)

The script name extraction in the health check uses a hardcoded regex pattern for /_scripts/c/, which won't work if users configure a custom collectPrefix.

View Details

Analysis

Hardcoded regex in health check fails with custom collectPrefix

What fails: The scripts-health.ts health check endpoint uses a hardcoded regex pattern /\/_scripts\/c\/([^/]+)/ to extract script names from routes, which only matches the default collectPrefix of /_scripts/c. When users configure a custom collectPrefix (e.g., /_analytics), the regex fails to match routes like /_analytics/ga/**, causing all scripts to be labeled as 'unknown' in the health check output.

How to reproduce:

  1. Configure custom collectPrefix in Nuxt config:
export default defineNuxtConfig({
  scripts: {
    firstParty: {
      collectPrefix: '/_analytics'
    }
  }
})
  1. Access the health check endpoint at /_scripts/health.json
  2. Observe that all scripts have script: 'unknown' instead of actual script names (ga, gtm, meta, etc.)

Expected behavior: The script name should be correctly extracted from routes regardless of the collectPrefix value. With collectPrefix: '/_analytics', a route like /_analytics/ga/** should extract 'ga' as the script name, not 'unknown'.

Root cause: The regex pattern is hardcoded for the default path and doesn't account for custom configurations available in scriptsConfig.collectPrefix.

// Use storage to cache the font data between builds
const cacheKey = `bundle:${filename}`
// Include proxy in cache key to differentiate proxied vs non-proxied versions
const cacheKey = proxyRewrites?.length ? `bundle-proxy:${filename}` : `bundle:${filename}`
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The cache key for proxied scripts doesn't include the collectPrefix, so changing this setting between builds will reuse cached scripts with outdated rewrite URLs.

View Details
πŸ“ Patch Details
diff --git a/src/plugins/transform.ts b/src/plugins/transform.ts
index 98e3aeb..8a497be 100644
--- a/src/plugins/transform.ts
+++ b/src/plugins/transform.ts
@@ -113,7 +113,9 @@ async function downloadScript(opts: {
   if (!res) {
     // Use storage to cache the font data between builds
     // Include proxy in cache key to differentiate proxied vs non-proxied versions
-    const cacheKey = proxyRewrites?.length ? `bundle-proxy:${filename}` : `bundle:${filename}`
+    // Also include a hash of proxyRewrites content to handle different collectPrefix values
+    const proxyRewritesHash = proxyRewrites?.length ? `-${ohash(proxyRewrites)}` : ''
+    const cacheKey = proxyRewrites?.length ? `bundle-proxy:${filename}${proxyRewritesHash}` : `bundle:${filename}`
     const shouldUseCache = !forceDownload && await storage.hasItem(cacheKey) && !(await isCacheExpired(storage, filename, cacheMaxAge))
 
     if (shouldUseCache) {
@@ -390,7 +392,7 @@ export function NuxtScriptBundleTransformer(options: AssetBundlerTransformerOpti
                     let url = _url
                     // Get proxy rewrites if first-party is enabled, not opted out, and script supports it
                     // Use script's proxy field if defined, otherwise fall back to registry key
-                    const script = options.scripts.find(s => s.import.name === fnName)
+                    const script = options.scripts?.find(s => s.import.name === fnName)
                     const proxyConfigKey = script?.proxy !== false ? (script?.proxy || registryKey) : undefined
                     const proxyRewrites = options.firstPartyEnabled && !firstPartyOptOut && proxyConfigKey && options.firstPartyCollectPrefix
                       ? getProxyConfig(proxyConfigKey, options.firstPartyCollectPrefix)?.rewrite

Analysis

Cache key mismatch when collectPrefix changes between builds

What fails: The cache key for proxied scripts in downloadScript() doesn't include the actual collectPrefix value, causing scripts cached with one configuration to be reused with different URL rewrites when the config changes within the cache TTL.

How to reproduce:

  1. Build with firstParty: { collectPrefix: '/_scripts/c' } - script URLs rewritten to /_scripts/c/ga/g/collect
  2. Within 7 days, change config to firstParty: { collectPrefix: '/_analytics' } and rebuild
  3. The cached script from step 1 is loaded from cache key bundle-proxy:filename
  4. Runtime expects requests at /_analytics/ga/... but cached script sends to /_scripts/c/ga/...
  5. Proxy requests fail because routes don't match the rewritten URLs

Result: Script gets wrong rewrite paths from cache, causing analytics/tracking requests to fail.

Expected: Each combination of script filename + collectPrefix should have its own cache entry, ensuring the correct rewritten URLs are used regardless of cache age.

Root cause: Line 116 in src/plugins/transform.ts creates cache key as bundle-proxy: when proxyRewrites?.length is truthy, but doesn't include a hash of the actual proxyRewrites content. Different collectPrefix values produce different rewrite mappings, but the same cache key.

Fix: Include hash of proxyRewrites in cache key: bundle-proxy:

Comment on lines 24 to 40
function rewriteScriptUrls(content: string, rewrites: ProxyRewrite[]): string {
let result = content
for (const { from, to } of rewrites) {
// Rewrite various URL formats
result = result
// Full URLs
.replaceAll(`"https://${from}`, `"${to}`)
.replaceAll(`'https://${from}`, `'${to}`)
.replaceAll(`\`https://${from}`, `\`${to}`)
.replaceAll(`"http://${from}`, `"${to}`)
.replaceAll(`'http://${from}`, `'${to}`)
.replaceAll(`\`http://${from}`, `\`${to}`)
.replaceAll(`"//${from}`, `"${to}`)
.replaceAll(`'//${from}`, `'${to}`)
.replaceAll(`\`//${from}`, `\`${to}`)
}
return result
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The rewriteScriptUrls function in proxy-handler.ts is an incomplete copy of the one in proxy-configs.ts, missing critical URL rewriting patterns needed for proper script proxying.

View Details
πŸ“ Patch Details
diff --git a/src/runtime/server/proxy-handler.ts b/src/runtime/server/proxy-handler.ts
index c5b30c3..1474f40 100644
--- a/src/runtime/server/proxy-handler.ts
+++ b/src/runtime/server/proxy-handler.ts
@@ -1,11 +1,7 @@
 import { defineEventHandler, getHeaders, getRequestIP, readBody, getQuery, setResponseHeader, createError } from 'h3'
 import { useRuntimeConfig } from '#imports'
 import { useNitroApp } from 'nitropack/runtime'
-
-interface ProxyRewrite {
-  from: string
-  to: string
-}
+import { rewriteScriptUrls, type ProxyRewrite } from '../../proxy-configs'
 
 interface ProxyConfig {
   routes: Record<string, string>
@@ -17,29 +13,6 @@ interface ProxyConfig {
   debug?: boolean
 }
 
-/**
- * Rewrite URLs in script content based on proxy config.
- * Inlined from proxy-configs.ts for runtime use.
- */
-function rewriteScriptUrls(content: string, rewrites: ProxyRewrite[]): string {
-  let result = content
-  for (const { from, to } of rewrites) {
-    // Rewrite various URL formats
-    result = result
-      // Full URLs
-      .replaceAll(`"https://${from}`, `"${to}`)
-      .replaceAll(`'https://${from}`, `'${to}`)
-      .replaceAll(`\`https://${from}`, `\`${to}`)
-      .replaceAll(`"http://${from}`, `"${to}`)
-      .replaceAll(`'http://${from}`, `'${to}`)
-      .replaceAll(`\`http://${from}`, `\`${to}`)
-      .replaceAll(`"//${from}`, `"${to}`)
-      .replaceAll(`'//${from}`, `'${to}`)
-      .replaceAll(`\`//${from}`, `\`${to}`)
-  }
-  return result
-}
-
 /**
  * Headers that reveal user IP address - always stripped in strict mode,
  * anonymized in anonymize mode.

Analysis

Missing URL rewriting patterns in proxy-handler.ts causes collection requests to bypass the proxy

What fails: The rewriteScriptUrls function in src/runtime/server/proxy-handler.ts (lines 24-40) is an incomplete copy that's missing critical URL rewriting patterns compared to the exported version in src/proxy-configs.ts. This causes JavaScript responses fetched through the proxy to retain unrewritten URLs for:

  1. Bare domain patterns (e.g., "api.segment.io" without protocol) - Segment SDK
  2. Google Analytics dynamic URL construction (e.g., "https://"+(...)+".google-analytics.com/g/collect") - Minified GA4 code

How to reproduce: Test with synthetic script content containing these patterns:

// Bare domain - NOT rewritten by old version
var apiHost = "api.segment.io/v1/batch";

// GA dynamic construction - NOT rewritten by old version  
var collect = "https://"+("www")+".google-analytics.com/g/collect";

Old inline version result: URLs remain unchanged, allowing collection requests to bypass proxy Fixed version result: URLs are properly rewritten to proxy paths

What happens vs expected:

  • Before fix: Collection endpoint requests embedded in JavaScript responses bypass the proxy and send data directly to third parties, exposing user IPs and defeating privacy protection
  • After fix: All collection requests are routed through the proxy and privacy-filtered based on configured mode

Root cause: src/runtime/server/proxy-handler.ts defines a local rewriteScriptUrls function (lines 24-40) instead of importing the complete exported version from src/proxy-configs.ts. The runtime version was missing the bare domain pattern handling (lines 267-269 in proxy-configs.ts) and Google Analytics dynamic construction regex patterns (lines 275-287 in proxy-configs.ts).

Fix implemented: Removed the incomplete inline function and imported the complete rewriteScriptUrls function from src/proxy-configs.ts.

Verification: All 180 unit tests pass, including the comprehensive third-party-proxy-replacements.test.ts which tests URL rewriting patterns for Google Analytics, Meta Pixel, TikTok, Segment, and other SDKs.

@harlan-zw harlan-zw mentioned this pull request Jan 23, 2026
@coderabbitai
Copy link

coderabbitai bot commented Jan 24, 2026

πŸ“ Walkthrough

Walkthrough

Adds a full First-Party Mode and proxy system to the Nuxt Scripts module. Key changes: new CLI (src/cli.ts) and package bin entry; module options/types for firstParty and privacy; build/runtime wiring for proxy prefixes and service worker support; server-side proxy handler, SW generator, and SW client registration; proxy-configs utility with rewrite rules and SW intercept rules; template and transformer updates to support serviceWorker triggers and proxy-aware bundling; many registry entries annotated with proxy keys; extensive docs and tests (unit, e2e, fixtures, snapshots) for proxying and privacy stripping; new runtime composables and dev-only status/health endpoints. A deleted .claude plan file is also removed.

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120 minutes

πŸš₯ Pre-merge checks | βœ… 4 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 52.78% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
βœ… Passed checks (4 passed)
Check name Status Explanation
Title check βœ… Passed The title 'feat: first-party mode' clearly summarizes the main feature addition and follows conventional commits format.
Description check βœ… Passed The PR description comprehensively covers linked issue, type of change, and detailed implementation explanation with code examples.
Linked Issues check βœ… Passed The PR successfully addresses issue #87 by implementing server-side proxying of third-party scripts, rewriting URLs at build time, and providing privacy-preserving features as specified.
Out of Scope Changes check βœ… Passed All changes are directly related to implementing first-party mode: proxy configuration, CLI tools, documentation, tests, and supporting infrastructure align with issue #87 objectives.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • πŸ“ Generate docstrings
πŸ§ͺ Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/proxy-scripts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❀️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 15

Note

Due to the large number of review comments, Critical, Major severity comments were prioritized as inline comments.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
docs/content/scripts/tracking/x-pixel.md (1)

17-18: Copy-paste error: "Meta Pixel" should be "X Pixel".

Line 17 incorrectly references "Meta Pixel" instead of "X Pixel".

πŸ“ Proposed fix
-The simplest way to load Meta Pixel globally in your Nuxt App is to use Nuxt config. Alternatively you can directly
+The simplest way to load X Pixel globally in your Nuxt App is to use Nuxt config. Alternatively you can directly
 use the [useScriptXPixel](`#useScriptXPixel`) composable.
src/assets.ts (1)

85-85: No-op push() call has no effect.

This line calls push() with no arguments, which does nothing. This appears to be a leftover from incomplete code or a copy-paste error.

Proposed fix
   nuxt.options.nitro.publicAssets ||= []
   const cacheDir = join(nuxt.options.buildDir, 'cache', 'scripts')
-  nuxt.options.nitro.publicAssets.push()
   nuxt.options.nitro = defu(nuxt.options.nitro, {
src/plugins/transform.ts (1)

103-167: Compute SRI after proxy rewrites to prevent integrity failures.
When proxyRewrites mutates content, the integrity hash (and cached metadata) reflects the pre‑rewrite bytes, which can cause browsers to reject the script when integrity is enabled. Compute the hash after rewrites (and consider scoping metadata per cacheKey if you support switching proxy/non‑proxy modes).

πŸ› Suggested fix (order of operations)
-    // Calculate integrity hash if enabled
-    const integrityHash = integrity && res
-      ? calculateIntegrity(res, integrity === true ? 'sha384' : integrity)
-      : undefined
-
-    await storage.setItemRaw(`bundle:${filename}`, res)
-    // Apply URL rewrites for proxy mode
-    if (proxyRewrites?.length && res) {
-      const content = res.toString('utf-8')
-      const rewritten = rewriteScriptUrls(content, proxyRewrites)
-      res = Buffer.from(rewritten, 'utf-8')
-      logger.debug(`Rewrote ${proxyRewrites.length} URL patterns in ${filename}`)
-    }
-
-    await storage.setItemRaw(cacheKey, res)
+    await storage.setItemRaw(`bundle:${filename}`, res)
+    // Apply URL rewrites for proxy mode
+    if (proxyRewrites?.length && res) {
+      const content = res.toString('utf-8')
+      const rewritten = rewriteScriptUrls(content, proxyRewrites)
+      res = Buffer.from(rewritten, 'utf-8')
+      logger.debug(`Rewrote ${proxyRewrites.length} URL patterns in ${filename}`)
+    }
+
+    // Calculate integrity hash after any rewrites so it matches served content
+    const integrityHash = integrity && res
+      ? calculateIntegrity(res, integrity === true ? 'sha384' : integrity)
+      : undefined
+
+    await storage.setItemRaw(cacheKey, res)
πŸ€– Fix all issues with AI agents
In `@src/module.ts`:
- Around line 389-393: Replace the direct console.log calls with the module's
logger (use this.logger.info) to comply with no-console: locate the
console.log('[nuxt-scripts] First-party config:', ...) in src/module.ts (and the
similar console.log at the later occurrence around the 496-499 area) and change
them to this.logger.info with the same message and object payload so the output
goes through Nuxt's logging system.
- Line 30: The import statement includes an unused type symbol ProxyConfig which
triggers a lint error; edit the import that currently lists getAllProxyConfigs,
getSWInterceptRules, ProxyConfig to remove ProxyConfig (or change it to an
explicit type-only import only where the type is actually used). Update any
references to ProxyConfig elsewhere if you intended to use it (either add a real
usage or import it with "import type { ProxyConfig } from './proxy-configs'") so
the module no longer imports an unused symbol.

In `@src/proxy-configs.ts`:
- Around line 198-231: The SWInterceptRule interface is missing the pathPrefix
property used by getSWInterceptRules and other runtime code; update the
SWInterceptRule declaration to include pathPrefix: string so its shape matches
how getSWInterceptRules (and sw-handler logic) builds rules from
buildProxyConfig, and ensure any exports/types referencing SWInterceptRule
reflect the added property.

In `@src/runtime/server/proxy-handler.ts`:
- Around line 395-425: The loop over originalHeaders currently forwards
non-fingerprinting headers (via headers[key] = value) which can leak
credentials; update proxy-handler.ts to drop a sensitive header denylist (e.g.,
'cookie', 'authorization', and any other session headers) unconditionally before
forwarding. In the header-processing block that checks lowerKey, add a check
against SENSITIVE_HEADERS (or inline list) and continue (skip) when matched,
ensuring functions like normalizeUserAgent and normalizeLanguage still run for
allowed headers but cookie/authorization are never copied into headers.
- Around line 324-327: The current debug logger uses console.log which ESLint
forbids; replace the log initializer in proxy-handler.ts that sets log = debug ?
console.log.bind(console) : () => {} to use the approved logger (e.g.,
logger.debug) or console.warn instead. Locate the proxyConfig destructure and
the log constant (symbols: proxyConfig, log) and change the truthy branch to
bind the project logger (e.g., logger.debug.bind(logger) or
logger.warn.bind(logger)); ensure the logger is imported or available in the
module and that fallback remains a no-op when debug is false.
- Around line 451-470: Split combined statements into separate lines in the JSON
and form-parsing blocks to satisfy `@stylistic/max-statements-per-line`: in the
rawBody JSON parsing section, move the JSON.parse assignment into its own line
inside the try block and put the empty catch block on its own line; in the
URL-encoded handling, expand the params.forEach callback so the assignment
obj[key] = value is on its own line inside the callback body; also separate the
creation of stripped and the conversion to a string so the const stripped =
stripPayloadFingerprinting(obj, privacyMode) and the body = new
URLSearchParams(stripped as Record<string, string>).toString() become two
distinct statements on separate lines. Reference symbols: rawBody, parsed,
stripPayloadFingerprinting, params.forEach, obj, stripped, body.
- Around line 485-486: Remove the unnecessary and unsafe TypeScript cast on the
hook call: replace the casted invocation "(nitro.hooks.callHook as
Function)('nuxt-scripts:proxy', {...})" with a direct call to
nitro.hooks.callHook('nuxt-scripts:proxy', {...}); update the invocation site in
proxy-handler.ts (the nitro.hooks.callHook usage) to call the method without "as
Function" so it uses the proper typed signature and satisfies the
no-unsafe-function-type rule.

In `@src/runtime/server/sw-handler.ts`:
- Around line 63-71: The service worker currently uses event.request.body
directly (inside event.respondWith when fetching proxyUrl.href), which will fail
if the body stream was consumed; update the handler to clone the incoming
request (use event.request.clone()) and read/forward the body from the clone
when constructing the fetch to proxyUrl.href so the original request stream
remains intact; adjust the logic around event.respondWith / fetch(proxyUrl.href,
{ method: event.request.method, headers: event.request.headers, body: ... }) to
use the cloned request's body and headers.

In `@src/runtime/sw/proxy-sw.ts`:
- Around line 4-7: The SWInterceptRule interface is missing the pathPrefix
property used by the code that constructs and consumes rules; update the
SWInterceptRule interface to include pathPrefix: string so it matches the
objects created in sw-handler (which builds { pattern, pathPrefix, target }) and
the generated service worker logic that reads rule.pathPrefix for
matching/stripping paths.

In `@test/e2e/__snapshots__/proxy/googleTagManager.json`:
- Around line 1-194: This snapshot file contains invalid trailing commas in JSON
objects (e.g., after "z": "0", inside the "original" and "stripped" objects and
other query objects); remove all trailing commas so each object and array uses
strict JSON syntax (for example edit the entries under "original" and "stripped"
query objects and the top-level array items to eliminate commas before closing
braces/brackets).

In `@test/e2e/first-party.test.ts`:
- Around line 190-196: The test currently uses console.log('[test] Proxy
error:', response) which violates the no-console lint rule; replace that
console.log call with console.warn or console.error so the lint rule is
satisfied (locate the call near writeFileSync(join(fixtureDir,
'proxy-test.json'), JSON.stringify(response, null, 2)) and the response object
check in first-party.test.ts and update the console invocation accordingly).

In `@test/fixtures/first-party/pages/segment.vue`:
- Around line 8-10: The call to useScriptSegment currently embeds a hardcoded
Segment writeKey; update the invocation of useScriptSegment to read the key from
an environment/config variable (e.g. SEGMENT_WRITE_KEY) with a non-secret
placeholder fallback so tests/fixtures do not contain credentials β€” locate the
useScriptSegment(...) call and replace the literal
'KBXOGxgqMFjm2mxtJDJg0iDn5AnGYb9C' with a lookup of the env/config value and a
clear placeholder default.

In `@test/unit/proxy-privacy.test.ts`:
- Around line 290-373: Move the stripFingerprintingFromPayload function out of
the test file into a shared test util module (e.g., create
test/utils/proxy-privacy.ts), export it from there, and update any tests
importing it to import from the new module; when moving, also import and
re-export or reference its dependencies (NORMALIZE_PARAMS, STRIP_PARAMS,
normalizeLanguage, normalizeUserAgent, anonymizeIP, generalizeScreen) inside the
new util so the function compiles, and remove the function export from the
original test file.
- Around line 176-285: Several tests in the "proxy privacy - payload analysis"
suite use console.log which violates the no-console rule; replace each
console.log(...) call in the GA, Meta, X/Twitter and generic fingerprint tests
(the ones logging 'GA fingerprinting params found', 'GA params to normalize',
'GA safe params', 'Meta fingerprinting params found', 'X/Twitter fingerprinting
params found', and 'All fingerprinting vectors:') with console.warn(...) or
remove the logging lines altogether so ESLint accepts them; update the
occurrences near the gaPayload/fingerprintParams, normalizeParams, safeParams,
metaPayload/fingerprintParams, xPayload/fingerprintParams, and fp/vectors
blocks.

In `@test/unit/third-party-proxy-replacements.test.ts`:
- Around line 1-5: Replace the cross-test import of
stripFingerprintingFromPayload from './proxy-privacy.test' with the shared
helper module where you extracted it; update the import statement to point to
the new shared util (the module that now exports stripFingerprintingFromPayload)
so tests import stripFingerprintingFromPayload from the shared utility instead
of another test file.
🟑 Minor comments (6)
test/e2e/__snapshots__/proxy/metaPixel.json-1-16 (1)

1-16: Remove trailing commas from JSON object literals.

The file contains invalid JSON syntax. Line 7 has a trailing comma after "query": {}, and the same issue appears on lines 13 and 15. Standard JSON parsers reject this format and will throw parse errors. Remove the trailing commas to make the JSON valid.

docs/content/docs/1.guides/2.first-party.md-523-552 (1)

523-552: Consent banner example has disconnected consent triggers.

The example creates consent triggers inline in useScriptGoogleAnalytics and useScriptMetaPixel (lines 532, 537), but acceptAll() calls acceptGA() and acceptMeta() which are from different useScriptTriggerConsent() instances (lines 526-527). This won't trigger the scripts.

πŸ“ Suggested fix
 <script setup>
 const hasConsent = ref(false)

-const { accept: acceptGA } = useScriptTriggerConsent()
-const { accept: acceptMeta } = useScriptTriggerConsent()
+const { status: gaStatus, accept: acceptGA } = useScriptTriggerConsent()
+const { status: metaStatus, accept: acceptMeta } = useScriptTriggerConsent()

 // Configure scripts with consent triggers
 useScriptGoogleAnalytics({
   id: 'G-XXXXXX',
-  scriptOptions: { trigger: useScriptTriggerConsent().status }
+  scriptOptions: { trigger: gaStatus }
 })

 useScriptMetaPixel({
   id: '123456',
-  scriptOptions: { trigger: useScriptTriggerConsent().status }
+  scriptOptions: { trigger: metaStatus }
 })

 function acceptAll() {
   hasConsent.value = true
   acceptGA()
   acceptMeta()
   // Scripts now load through first-party proxy
 }
src/runtime/server/api/scripts-health.ts-81-82 (1)

81-82: Guard against division by zero when no routes are configured.

If scriptsConfig.routes is empty, checks.length will be 0, causing avgLatency to be NaN.

Proposed fix
   const allOk = checks.every(c => c.status === 'ok')
-  const avgLatency = checks.reduce((sum, c) => sum + (c.latency || 0), 0) / checks.length
+  const avgLatency = checks.length > 0
+    ? checks.reduce((sum, c) => sum + (c.latency || 0), 0) / checks.length
+    : 0
src/runtime/server/api/scripts-health.ts-38-40 (1)

38-40: Incomplete regex escaping β€” backslashes not escaped.

The escaping only handles forward slashes. For robustness, also escape backslashes and other regex metacharacters. While collectPrefix is unlikely to contain such characters, this ensures correctness.

Proposed fix
-  const escapedPrefix = scriptsConfig.collectPrefix.replace(/\//g, '\\/')
+  const escapedPrefix = scriptsConfig.collectPrefix.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
src/cli.ts-122-134 (1)

122-134: Add timeout to health check fetch to prevent indefinite hangs.

The fetch call has no timeout. If the server is unresponsive, the CLI will hang indefinitely. Also, line 123 has a redundant default since args.port already defaults to '3000' in the args definition.

Proposed fix
       async run({ args }) {
-        const port = args.port || '3000'
+        const port = args.port
         const url = `http://localhost:${port}/_scripts/health.json`

         consola.info(`Checking health at ${url}...`)

-        const res = await fetch(url)
+        const res = await fetch(url, { signal: AbortSignal.timeout(10000) })
           .then(r => r.json())
           .catch((err) => {
-            consola.error(`Failed to connect: ${err.message}`)
+            const message = err.name === 'TimeoutError' ? 'Request timed out' : err.message
+            consola.error(`Failed to connect: ${message}`)
             consola.info('Make sure the dev server is running with `nuxi dev`')
             return null
           })
src/module.ts-55-60 (1)

55-60: Doc default for collectPrefix doesn’t match implementation.

JSDoc says / _scripts/c, but the code defaults to / _proxy. Align the docs (or default) to avoid confusion.

πŸ› οΈ Proposed fix
-   * `@default` '/_scripts/c'
+   * `@default` '/_proxy'
🧹 Nitpick comments (5)
test/fixtures/first-party/server/plugins/capture-proxy.ts (1)

7-13: Consider async file operations and improved typing.

For a test fixture this is acceptable, but note:

  1. Synchronous writeFileSync/mkdirSync can block the event loop during concurrent proxy events
  2. data: any loses type information β€” consider a typed interface
  3. No guard if data.timestamp is undefined (would produce capture-undefined.json)
♻️ Optional improvement with async operations
-import { writeFileSync, mkdirSync } from 'node:fs'
+import { writeFile, mkdir } from 'node:fs/promises'
 import { join } from 'node:path'
 
 // Use NUXT_SCRIPTS_CAPTURE_DIR env var or default to rootDir/.captures
 const captureDir = process.env.NUXT_SCRIPTS_CAPTURE_DIR || join(process.cwd(), '.captures')
 
+interface ProxyEventData {
+  timestamp: number
+  [key: string]: unknown
+}
+
 export default defineNitroPlugin((nitro) => {
-  nitro.hooks.hook('nuxt-scripts:proxy', (data: any) => {
+  nitro.hooks.hook('nuxt-scripts:proxy', async (data: ProxyEventData) => {
     // Ensure dir exists before each write (handles race conditions)
-    mkdirSync(captureDir, { recursive: true })
-    const filename = join(captureDir, `capture-${data.timestamp}.json`)
-    writeFileSync(filename, JSON.stringify(data, null, 2))
+    await mkdir(captureDir, { recursive: true })
+    const filename = join(captureDir, `capture-${data.timestamp ?? Date.now()}.json`)
+    await writeFile(filename, JSON.stringify(data, null, 2))
   })
 })
src/runtime/composables/useScriptTriggerServiceWorker.ts (1)

47-51: Race condition: scope disposal may resolve an already-settled promise.

If the promise already resolved via done() (from controllerchange or timeout), the tryOnScopeDispose callback will still call resolve(false). While this won't throw in JavaScript (calling resolve multiple times is a no-op on an already-settled promise), the cleanup should use the same guard pattern for consistency and clarity.

♻️ Suggested fix
     tryOnScopeDispose(() => {
       navigator.serviceWorker.removeEventListener('controllerchange', onControllerChange)
       clearTimeout(timer)
-      resolve(false)
+      if (!resolved) {
+        resolved = true
+        resolve(false)
+      }
     })
src/runtime/server/api/scripts-health.ts (1)

19-19: Prefix unused parameter with underscore.

The event parameter is defined but never used. Prefix it with an underscore to satisfy the linter.

Proposed fix
-export default defineEventHandler(async (event) => {
+export default defineEventHandler(async (_event) => {
test/unit/first-party.test.ts (1)

2-2: Remove unused import.

getProxyConfig is imported but never used in this test file.

Proposed fix
-import { getAllProxyConfigs, getProxyConfig } from '../../src/proxy-configs'
+import { getAllProxyConfigs } from '../../src/proxy-configs'
src/cli.ts (1)

92-100: Consider handling prompt cancellation (Ctrl+C).

If the user cancels the prompt with Ctrl+C, consola.prompt may throw an error or return undefined. The current check if (!confirmed) handles false and falsy values, but you may want to wrap this in a try-catch for cleaner handling.

Comment on lines 389 to 393
// Pre-resolve paths needed for hooks
const swHandlerPath = await resolvePath('./runtime/server/sw-handler')

console.log('[nuxt-scripts] First-party config:', { firstPartyEnabled, firstPartyPrivacy, firstPartyCollectPrefix })

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Replace console.log with module logger to satisfy no-console.

πŸ› οΈ Proposed fix
-    console.log('[nuxt-scripts] First-party config:', { firstPartyEnabled, firstPartyPrivacy, firstPartyCollectPrefix })
+    logger.debug('[nuxt-scripts] First-party config:', { firstPartyEnabled, firstPartyPrivacy, firstPartyCollectPrefix })
 ...
-        console.log('[nuxt-scripts] Registering proxy handler:', `${firstPartyCollectPrefix}/**`, '->', proxyHandlerPath)
+        logger.debug('[nuxt-scripts] Registering proxy handler:', `${firstPartyCollectPrefix}/**`, '->', proxyHandlerPath)

Also applies to: 496-499

🧰 Tools
πŸͺ› ESLint

[error] 392-392: Unexpected console statement. Only these console methods are allowed: warn, error.

(no-console)

πŸ€– Prompt for AI Agents
In `@src/module.ts` around lines 389 - 393, Replace the direct console.log calls
with the module's logger (use this.logger.info) to comply with no-console:
locate the console.log('[nuxt-scripts] First-party config:', ...) in
src/module.ts (and the similar console.log at the later occurrence around the
496-499 area) and change them to this.logger.info with the same message and
object payload so the output goes through Nuxt's logging system.

Comment on lines +198 to +231
export interface SWInterceptRule {
/** Domain pattern to match (supports wildcards like *.google-analytics.com) */
pattern: string
/** Path prefix to match and strip from the original URL (e.g., /tr for www.facebook.com/tr) */
pathPrefix: string
/** Local path prefix to rewrite to */
target: string
}

/**
* Get service worker intercept rules from all proxy configs.
* These rules are used by the SW to intercept and rewrite outbound requests.
*/
export function getSWInterceptRules(collectPrefix: string): SWInterceptRule[] {
const configs = buildProxyConfig(collectPrefix)
const rules: SWInterceptRule[] = []

// Extract unique domain -> target mappings from route rules
for (const config of Object.values(configs)) {
if (!config.routes)
continue
for (const [localPath, { proxy }] of Object.entries(config.routes)) {
// Extract domain and path prefix from proxy URL
// e.g., "https://www.facebook.com/tr/**" -> domain="www.facebook.com", pathPrefix="/tr"
// e.g., "https://connect.facebook.net/**" -> domain="connect.facebook.net", pathPrefix=""
const match = proxy.match(/^https?:\/\/([^/]+)(\/.*)?\/\*\*$/)
if (match?.[1]) {
const domain = match[1]
// Path prefix is everything between domain and /** (e.g., /tr), empty if none
const pathPrefix = match[2] || ''
// Extract target prefix: "/_proxy/meta-tr/**" -> "/_proxy/meta-tr"
const target = localPath.replace(/\/\*\*$/, '')
rules.push({ pattern: domain, pathPrefix, target })
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Search for SWInterceptRule definition and pathPrefix usage
echo "=== Searching for SWInterceptRule definition ==="
rg -n "interface SWInterceptRule|type SWInterceptRule" src/

echo -e "\n=== Searching for pathPrefix usage in runtime ==="
rg -n "pathPrefix" src/runtime/

echo -e "\n=== Checking getSWInterceptRules usage ==="
rg -n "getSWInterceptRules" src/

Repository: nuxt/scripts

Length of output: 1163


🏁 Script executed:

#!/bin/bash
# Check SWInterceptRule definition in src/runtime/sw/proxy-sw.ts
echo "=== src/runtime/sw/proxy-sw.ts (around line 4) ==="
sed -n '1,20p' src/runtime/sw/proxy-sw.ts

echo -e "\n=== src/runtime/server/sw-handler.ts (full file to see pathPrefix usage) ==="
cat -n src/runtime/server/sw-handler.ts

Repository: nuxt/scripts

Length of output: 4088


SWInterceptRule interface in src/runtime/sw/proxy-sw.ts is missing the pathPrefix field.

The interface definition (line 4–6) only includes pattern and target, but src/runtime/server/sw-handler.ts generates rules with pathPrefix (line 18) and the generated code actively uses it to match and strip path prefixes from URLs (lines 54, 58–59). Update the interface to include pathPrefix: string to align with the actual implementation.

πŸ€– Prompt for AI Agents
In `@src/proxy-configs.ts` around lines 198 - 231, The SWInterceptRule interface
is missing the pathPrefix property used by getSWInterceptRules and other runtime
code; update the SWInterceptRule declaration to include pathPrefix: string so
its shape matches how getSWInterceptRules (and sw-handler logic) builds rules
from buildProxyConfig, and ensure any exports/types referencing SWInterceptRule
reflect the added property.

Comment on lines 8 to 10
const { proxy, status } = useScriptSegment({
writeKey: 'KBXOGxgqMFjm2mxtJDJg0iDn5AnGYb9C',
})
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

# First, let's examine the file in question
cat -n test/fixtures/first-party/pages/segment.vue

Repository: nuxt/scripts

Length of output: 1142


🏁 Script executed:

# Search for this specific writeKey across the entire codebase
rg 'KBXOGxgqMFjm2mxtJDJg0iDn5AnGYb9C' --type-list

Repository: nuxt/scripts

Length of output: 445


🏁 Script executed:

# Look for Segment write keys or similar patterns in the codebase
rg 'writeKey' -t js -t vue -t ts -A 2 -B 2

Repository: nuxt/scripts

Length of output: 83


🏁 Script executed:

# Check if there's any documentation about test fixtures or keys
find . -name "README*" -o -name "TESTING*" -o -name ".env*" | head -20

Repository: nuxt/scripts

Length of output: 1883


🏁 Script executed:

# Look for gitleaks or other security scanning configs
find . -name ".gitleaks*" -o -name "*.gitleaks*" -o -name "secrets*" 2>/dev/null

Repository: nuxt/scripts

Length of output: 38


🏁 Script executed:

# Search for the exact writeKey across entire codebase
rg 'KBXOGxgqMFjm2mxtJDJg0iDn5AnGYb9C'

Repository: nuxt/scripts

Length of output: 901


🏁 Script executed:

# Search for writeKey patterns
rg 'writeKey' -A 1 -B 1

Repository: nuxt/scripts

Length of output: 2628


🏁 Script executed:

# Check .env.example for fixture documentation
cat -n docs/.env.example

Repository: nuxt/scripts

Length of output: 276


🏁 Script executed:

# Look for test configuration and fixture setup docs
find . -path ./node_modules -prune -o -type f \( -name "*.md" -o -name "*.txt" \) -print | xargs grep -l "Segment\|fixture" 2>/dev/null | head -10

Repository: nuxt/scripts

Length of output: 191


🏁 Script executed:

# Check if this key pattern matches Segment's documentation or public test keys
rg 'test.*key\|fixture.*key\|public.*key' -i --type-list | head -5

Repository: nuxt/scripts

Length of output: 445


🏁 Script executed:

# Check how environment variables are used in tests and fixtures
rg 'process.env\|NUXT_' test/fixtures -A 1 -B 1 | head -30

Repository: nuxt/scripts

Length of output: 38


🏁 Script executed:

# Look at the git history to see if this key was always used or if there's context
git log --oneline -20 -- test/fixtures/first-party/pages/segment.vue 2>/dev/null | head -5

Repository: nuxt/scripts

Length of output: 134


🏁 Script executed:

# Check Segment documentation to see if this is a known test/public key
web_search
Segment 'KBXOGxgqMFjm2mxtJDJg0iDn5AnGYb9C' test writeKey

Repository: nuxt/scripts

Length of output: 152


🏁 Script executed:

# Look at whether this is documented as a test fixture
grep -r 'KBXOGxgqMFjm2mxtJDJg0iDn5AnGYb9C' docs/ | head -5

Repository: nuxt/scripts

Length of output: 38


🌐 Web query:

Segment writeKey test fixture dummy public key

πŸ’‘ Result:

There isn’t a β€œpublic dummy Segment writeKey” you can safely use as a universal test keyβ€”Segment writeKeys are per-source credentials, so for anything that actually sends events you should create a separate dev/test Source in your own workspace and use its writeKey. (twilio.com)

If you just need a test fixture string (non-working, for unit tests/mocks), Segment’s own docs/snippets commonly use placeholders like "writekey" / 'SEGMENT_API_KEY'. (segment-docs.netlify.app)

If you want an example-looking key for fixtures, Segment’s HTTP API doc includes a sample writeKey value (as an example payload): DmBXIN4JnwqBnTqXccTF0wBnLXNQmFtk (treat as documentation sample only; don’t expect it to authenticate). (segment-docs.netlify.app)

Citations:


🏁 Script executed:

# Check the Segment documentation in the repo itself
cat -n docs/content/scripts/tracking/segment.md | head -100

Repository: nuxt/scripts

Length of output: 2980


🏁 Script executed:

# Look at other fixture files to understand the pattern
ls -la test/fixtures/first-party/

Repository: nuxt/scripts

Length of output: 745


🏁 Script executed:

# Check if there's any documentation about test fixtures or credentials
find . -path ./node_modules -prune -o -type f -name "*.md" -print | xargs grep -l "test key\|fixture\|credential" 2>/dev/null

Repository: nuxt/scripts

Length of output: 194


Replace hardcoded Segment writeKey with environment variable or placeholder.

Line 9 contains a hardcoded writeKey. Segment writeKeys are authentication credentials tied to specific sources. Even if this is a test key, hardcoding credentials in fixtures exposes them in version control. Use an environment variable with a placeholder fallback instead.

Example fix
-const { proxy, status } = useScriptSegment({
-  writeKey: 'KBXOGxgqMFjm2mxtJDJg0iDn5AnGYb9C',
-})
+const { proxy, status } = useScriptSegment({
+  writeKey: process.env.NUXT_PUBLIC_SCRIPTS_SEGMENT_WRITE_KEY ?? 'YOUR_WRITE_KEY',
+})
πŸ“ Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const { proxy, status } = useScriptSegment({
writeKey: 'KBXOGxgqMFjm2mxtJDJg0iDn5AnGYb9C',
})
const { proxy, status } = useScriptSegment({
writeKey: process.env.NUXT_PUBLIC_SCRIPTS_SEGMENT_WRITE_KEY ?? 'YOUR_WRITE_KEY',
})
🧰 Tools
πŸͺ› Gitleaks (8.30.0)

[high] 9-9: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

πŸ€– Prompt for AI Agents
In `@test/fixtures/first-party/pages/segment.vue` around lines 8 - 10, The call to
useScriptSegment currently embeds a hardcoded Segment writeKey; update the
invocation of useScriptSegment to read the key from an environment/config
variable (e.g. SEGMENT_WRITE_KEY) with a non-secret placeholder fallback so
tests/fixtures do not contain credentials β€” locate the useScriptSegment(...)
call and replace the literal 'KBXOGxgqMFjm2mxtJDJg0iDn5AnGYb9C' with a lookup of
the env/config value and a clear placeholder default.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

πŸ€– Fix all issues with AI agents
In `@src/runtime/server/api/scripts-health.ts`:
- Line 23: The exported default handler defineEventHandler currently declares an
unused parameter named event; rename it to _event (or prefix with an underscore)
in the defineEventHandler signature to silence ESLint unused-variable warnings
while preserving the async handler behavior and function identity (i.e., change
"async (event) =>" to "async (_event) =>" in the default export).

In `@test/e2e/first-party.test.ts`:
- Around line 526-536: Remove the duplicated comment block about Clarity and
Hotjar in first-party.test.ts by keeping a single copy and deleting the
redundant copy; locate the two identical comment paragraphs (the repeated notes
beginning "Note: Clarity and Hotjar are session recording tools...") and remove
one so only one explanatory comment remains, preserving surrounding whitespace
and formatting.

In `@test/unit/proxy-privacy.test.ts`:
- Around line 359-360: Add a single trailing newline character at the end of
proxy-privacy.test.ts so the file ends with a newline (i.e., after the final
closing "})" add one blank line/line break), then save/commit so ESLint no
longer reports "Missing newline at end of file".
♻️ Duplicate comments (4)
src/runtime/server/proxy-handler.ts (4)

445-446: Remove as Function cast from callHook invocation.

The cast violates @typescript-eslint/no-unsafe-function-type. Nitro's callHook is properly typed - other usages in the codebase don't require this cast. If there's a type error, consider augmenting the hook types instead.

πŸ”§ Proposed fix
-  await (nitro.hooks.callHook as Function)('nuxt-scripts:proxy', {
+  await nitro.hooks.callHook('nuxt-scripts:proxy', {

412-430: Split multi-statement lines to satisfy @stylistic/max-statements-per-line.

Lines 414 and 428 each have 2 statements, violating the style rule.

πŸ”§ Proposed fix
         if (rawBody.startsWith('{') || rawBody.startsWith('[')) {
           let parsed: unknown = null
-          try { parsed = JSON.parse(rawBody) }
-          catch { /* not valid JSON */ }
+          try {
+            parsed = JSON.parse(rawBody)
+          }
+          catch {
+            /* not valid JSON */
+          }

           if (parsed && typeof parsed === 'object') {
             body = stripPayloadFingerprinting(parsed as Record<string, unknown>, privacyMode)
@@ -424,7 +428,9 @@ export default defineEventHandler(async (event) => {
         else if (contentType.includes('application/x-www-form-urlencoded')) {
           // URL-encoded form data
           const params = new URLSearchParams(rawBody)
           const obj: Record<string, unknown> = {}
-          params.forEach((value, key) => { obj[key] = value })
+          params.forEach((value, key) => {
+            obj[key] = value
+          })
           const stripped = stripPayloadFingerprinting(obj, privacyMode)

6-9: Remove unused ProxyRewrite interface.

This interface is defined but never used. The rewriteScriptUrls function is imported from proxy-configs.ts which has its own type definitions.

πŸ”§ Proposed fix
-interface ProxyRewrite {
-  from: string
-  to: string
-}
-

280-282: Replace console.debug with allowed console method.

ESLint only allows console.warn and console.error. Use console.warn for debug output or inject a logger.

πŸ”§ Proposed fix
-  const log = debug ? console.debug.bind(console) : () => {}
+  const log = debug ? console.warn.bind(console) : () => {}
🧹 Nitpick comments (3)
src/runtime/server/api/scripts-health.ts (1)

57-80: Consider adding error handling for malformed targets.

If target.replace('/**', '/') produces an invalid URL, the fetch will throw. While the catch block handles this, consider validating the URL construction or providing more specific error messages.

♻️ Optional improvement
     // Convert wildcard target to a testable URL
     const testUrl = target.replace('/**', '/')

     const start = Date.now()
+
+    // Validate URL before fetching
+    try {
+      new URL(testUrl)
+    }
+    catch {
+      checks.push({
+        script: scriptName,
+        route,
+        target: testUrl,
+        status: 'error',
+        error: 'Invalid target URL',
+      })
+      continue
+    }

     const result = await fetch(testUrl, {
test/unit/third-party-proxy-replacements.test.ts (2)

81-136: Avoid live network fetches in unit tests.

Real vendor downloads can be flaky and the catch+return makes failures silently pass; prefer deterministic fixtures/mocks or gate this check behind an explicit opt‑in so regressions don’t slip unnoticed.


557-611: Consider gating the verbose comparison output.

console.warn on every run can be noisy in CI; optionally guard behind a debug/env flag.

*
* Tests a sample request to each proxy route to verify connectivity.
*/
export default defineEventHandler(async (event) => {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟑 Minor

Prefix unused event parameter.

ESLint flags unused variables. Prefix with underscore to indicate intentional non-use.

πŸ”§ Proposed fix
-export default defineEventHandler(async (event) => {
+export default defineEventHandler(async (_event) => {
πŸ“ Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export default defineEventHandler(async (event) => {
export default defineEventHandler(async (_event) => {
🧰 Tools
πŸͺ› ESLint

[error] 23-23: 'event' is defined but never used. Allowed unused args must match /^_/u.

(@typescript-eslint/no-unused-vars)

πŸ€– Prompt for AI Agents
In `@src/runtime/server/api/scripts-health.ts` at line 23, The exported default
handler defineEventHandler currently declares an unused parameter named event;
rename it to _event (or prefix with an underscore) in the defineEventHandler
signature to silence ESLint unused-variable warnings while preserving the async
handler behavior and function identity (i.e., change "async (event) =>" to
"async (_event) =>" in the default export).

Comment on lines +526 to +536
// Note: Clarity and Hotjar are session recording tools that primarily use:
// - Clarity: d.clarity.ms (data collection) - may buffer data before sending
// - Hotjar: WebSocket connections (wss://ws*.hotjar.com) which can't be proxied via HTTP
// These tests verify the script loads and proxy config is correct.
// Data collection may not occur in short headless sessions.

// Note: Clarity and Hotjar are session recording tools that primarily use:
// - Clarity: d.clarity.ms (data collection) - may buffer data before sending
// - Hotjar: WebSocket connections (wss://ws*.hotjar.com) which can't be proxied via HTTP
// These tests verify page loads and proxy config is correct.
// Data collection may not occur in short headless sessions.
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟑 Minor

Remove duplicate comment block.

Lines 526-530 and 532-536 contain the same comment about Clarity and Hotjar limitations. This appears to be a copy-paste artifact.

πŸ”§ Proposed fix
     // Note: Clarity and Hotjar are session recording tools that primarily use:
     // - Clarity: d.clarity.ms (data collection) - may buffer data before sending
     // - Hotjar: WebSocket connections (wss://ws*.hotjar.com) which can't be proxied via HTTP
     // These tests verify the script loads and proxy config is correct.
     // Data collection may not occur in short headless sessions.
-
-    // Note: Clarity and Hotjar are session recording tools that primarily use:
-    // - Clarity: d.clarity.ms (data collection) - may buffer data before sending
-    // - Hotjar: WebSocket connections (wss://ws*.hotjar.com) which can't be proxied via HTTP
-    // These tests verify page loads and proxy config is correct.
-    // Data collection may not occur in short headless sessions.

     it('clarity', async () => {
πŸ€– Prompt for AI Agents
In `@test/e2e/first-party.test.ts` around lines 526 - 536, Remove the duplicated
comment block about Clarity and Hotjar in first-party.test.ts by keeping a
single copy and deleting the redundant copy; locate the two identical comment
paragraphs (the repeated notes beginning "Note: Clarity and Hotjar are session
recording tools...") and remove one so only one explanatory comment remains,
preserving surrounding whitespace and formatting.

Comment on lines +359 to +360
})
}) No newline at end of file
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟑 Minor

Missing newline at end of file.

ESLint requires a newline at the end of the file.

πŸ”§ Proposed fix
 })
+
πŸ“ Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
})
})
})
})
🧰 Tools
πŸͺ› ESLint

[error] 360-360: Newline required at end of file but not found.

(@stylistic/eol-last)

πŸ€– Prompt for AI Agents
In `@test/unit/proxy-privacy.test.ts` around lines 359 - 360, Add a single
trailing newline character at the end of proxy-privacy.test.ts so the file ends
with a newline (i.e., after the final closing "})" add one blank line/line
break), then save/commit so ESLint no longer reports "Missing newline at end of
file".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Investigate offloading entire scripts as a server proxy

2 participants