@c15t/scripts 2.2.0 → 3.0.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (197) hide show
  1. package/AGENTS.md +74 -48
  2. package/README.md +3 -3
  3. package/dist/e2e-test-utils.js +60 -24
  4. package/dist/engine/compile.js +45 -45
  5. package/dist/engine/runtime.js +119 -119
  6. package/dist/registry.js +186 -176
  7. package/dist/resolve.js +12 -12
  8. package/dist/vendors/_shared/attributes.js +5 -5
  9. package/dist/vendors/_shared/google-consent.js +10 -10
  10. package/dist/vendors/_shared/install-builders.js +9 -9
  11. package/dist/vendors/_shared/script-url.js +12 -12
  12. package/dist/vendors/ads-and-pixels/linkedin-insights.js +16 -16
  13. package/dist/vendors/ads-and-pixels/meta-pixel.js +82 -82
  14. package/dist/vendors/ads-and-pixels/microsoft-uet.js +57 -57
  15. package/dist/vendors/ads-and-pixels/openai-pixel.js +88 -0
  16. package/dist/vendors/ads-and-pixels/reddit-pixel.js +39 -39
  17. package/dist/vendors/ads-and-pixels/snapchat-pixel.js +25 -25
  18. package/dist/vendors/ads-and-pixels/tiktok-pixel.js +31 -31
  19. package/dist/vendors/ads-and-pixels/x-pixel.js +17 -17
  20. package/dist/vendors/analytics/adobe-analytics.js +17 -17
  21. package/dist/vendors/analytics/ahrefs-analytics.js +8 -8
  22. package/dist/vendors/analytics/amplitude.js +39 -39
  23. package/dist/vendors/analytics/clearbit.js +11 -11
  24. package/dist/vendors/analytics/cloudflare-web-analytics.js +13 -13
  25. package/dist/vendors/analytics/databuddy.js +45 -45
  26. package/dist/vendors/analytics/fathom-analytics.js +15 -15
  27. package/dist/vendors/analytics/google-tag.js +23 -23
  28. package/dist/vendors/analytics/heap.js +37 -37
  29. package/dist/vendors/analytics/hightouch.js +30 -30
  30. package/dist/vendors/analytics/hotjar.js +14 -14
  31. package/dist/vendors/analytics/logrocket.js +24 -24
  32. package/dist/vendors/analytics/matomo-analytics.js +51 -51
  33. package/dist/vendors/analytics/microsoft-clarity.js +31 -31
  34. package/dist/vendors/analytics/mixpanel-analytics.js +31 -31
  35. package/dist/vendors/analytics/pirsch.js +27 -27
  36. package/dist/vendors/analytics/plausible-analytics.js +24 -24
  37. package/dist/vendors/analytics/posthog.js +84 -79
  38. package/dist/vendors/analytics/promptwatch.js +8 -8
  39. package/dist/vendors/analytics/rudderstack.js +50 -50
  40. package/dist/vendors/analytics/rybbit-analytics.js +30 -30
  41. package/dist/vendors/analytics/segment.js +16 -16
  42. package/dist/vendors/analytics/umami-analytics.js +16 -16
  43. package/dist/vendors/analytics/vercel-analytics.js +22 -22
  44. package/dist/vendors/functional/crisp.js +49 -51
  45. package/dist/vendors/functional/intercom.js +18 -18
  46. package/dist/vendors/tag-managers/google-tag-manager.js +20 -20
  47. package/dist-types/__tests__/helpers.d.ts +10 -10
  48. package/dist-types/engine/compile.d.ts +2 -2
  49. package/dist-types/engine/runtime.d.ts +3 -3
  50. package/dist-types/registry.d.ts +182 -173
  51. package/dist-types/resolve.d.ts +2 -2
  52. package/dist-types/types.d.ts +2 -2
  53. package/dist-types/vendors/_shared/attributes.d.ts +2 -2
  54. package/dist-types/vendors/_shared/google-consent.d.ts +2 -2
  55. package/dist-types/vendors/_shared/install-builders.d.ts +1 -1
  56. package/dist-types/vendors/_shared/script-url.d.ts +6 -6
  57. package/dist-types/vendors/ads-and-pixels/linkedin-insights.d.ts +14 -14
  58. package/dist-types/vendors/ads-and-pixels/meta-pixel.d.ts +27 -27
  59. package/dist-types/vendors/ads-and-pixels/microsoft-uet.d.ts +40 -40
  60. package/dist-types/vendors/ads-and-pixels/openai-pixel.d.ts +211 -0
  61. package/dist-types/vendors/ads-and-pixels/reddit-pixel.d.ts +28 -29
  62. package/dist-types/vendors/ads-and-pixels/snapchat-pixel.d.ts +23 -23
  63. package/dist-types/vendors/ads-and-pixels/tiktok-pixel.d.ts +22 -22
  64. package/dist-types/vendors/ads-and-pixels/x-pixel.d.ts +15 -15
  65. package/dist-types/vendors/analytics/adobe-analytics.d.ts +3 -3
  66. package/dist-types/vendors/analytics/ahrefs-analytics.d.ts +5 -5
  67. package/dist-types/vendors/analytics/amplitude.d.ts +24 -24
  68. package/dist-types/vendors/analytics/clearbit.d.ts +5 -5
  69. package/dist-types/vendors/analytics/cloudflare-web-analytics.d.ts +6 -6
  70. package/dist-types/vendors/analytics/databuddy.d.ts +34 -31
  71. package/dist-types/vendors/analytics/fathom-analytics.d.ts +8 -8
  72. package/dist-types/vendors/analytics/google-tag.d.ts +17 -17
  73. package/dist-types/vendors/analytics/heap.d.ts +17 -17
  74. package/dist-types/vendors/analytics/hightouch.d.ts +15 -15
  75. package/dist-types/vendors/analytics/hotjar.d.ts +9 -9
  76. package/dist-types/vendors/analytics/logrocket.d.ts +11 -11
  77. package/dist-types/vendors/analytics/matomo-analytics.d.ts +3 -3
  78. package/dist-types/vendors/analytics/microsoft-clarity.d.ts +12 -13
  79. package/dist-types/vendors/analytics/mixpanel-analytics.d.ts +20 -20
  80. package/dist-types/vendors/analytics/pirsch.d.ts +10 -10
  81. package/dist-types/vendors/analytics/plausible-analytics.d.ts +13 -13
  82. package/dist-types/vendors/analytics/posthog.d.ts +35 -32
  83. package/dist-types/vendors/analytics/promptwatch.d.ts +5 -5
  84. package/dist-types/vendors/analytics/rudderstack.d.ts +16 -16
  85. package/dist-types/vendors/analytics/rybbit-analytics.d.ts +15 -15
  86. package/dist-types/vendors/analytics/segment.d.ts +11 -11
  87. package/dist-types/vendors/analytics/umami-analytics.d.ts +9 -9
  88. package/dist-types/vendors/analytics/vercel-analytics.d.ts +13 -13
  89. package/dist-types/vendors/functional/crisp.d.ts +9 -9
  90. package/dist-types/vendors/functional/intercom.d.ts +12 -12
  91. package/dist-types/vendors/tag-managers/google-tag-manager.d.ts +16 -16
  92. package/docs/README.md +74 -48
  93. package/docs/assets/v3/brand-bar.png +0 -0
  94. package/docs/assets/v3/brand-card.png +0 -0
  95. package/docs/assets/v3/choice-wall.png +0 -0
  96. package/docs/assets/v3/mobile-card.png +0 -0
  97. package/docs/assets/v3/preferences.png +0 -0
  98. package/docs/customization/overview.md +45 -0
  99. package/docs/customization/recipes.md +79 -0
  100. package/docs/customization/slots.md +55 -0
  101. package/docs/customization/tokens.md +76 -0
  102. package/docs/customization/translations.md +49 -0
  103. package/docs/frameworks/javascript/script-loader.md +30 -339
  104. package/docs/frameworks/next/script-loader.md +134 -467
  105. package/docs/frameworks/react/script-loader.md +35 -535
  106. package/docs/guides/consent-state.md +60 -0
  107. package/docs/guides/data-fetching.md +163 -0
  108. package/docs/guides/deployment-modes.md +63 -0
  109. package/docs/guides/troubleshooting.md +68 -0
  110. package/docs/guides/verify-consent.md +62 -0
  111. package/docs/integrations/adobe-analytics.md +239 -105
  112. package/docs/integrations/ahrefs-analytics.md +238 -104
  113. package/docs/integrations/amplitude.md +219 -157
  114. package/docs/integrations/building-integrations.md +32 -224
  115. package/docs/integrations/clearbit.md +247 -86
  116. package/docs/integrations/cloudflare-web-analytics.md +250 -84
  117. package/docs/integrations/crisp.md +251 -97
  118. package/docs/integrations/databuddy.md +259 -153
  119. package/docs/integrations/fathom-analytics.md +239 -96
  120. package/docs/integrations/google-maps.md +328 -207
  121. package/docs/integrations/google-tag-manager.md +248 -96
  122. package/docs/integrations/google-tag.md +261 -90
  123. package/docs/integrations/heap.md +222 -149
  124. package/docs/integrations/hightouch.md +225 -131
  125. package/docs/integrations/hotjar.md +239 -90
  126. package/docs/integrations/intercom.md +239 -98
  127. package/docs/integrations/linkedin-insights.md +243 -113
  128. package/docs/integrations/logrocket.md +241 -123
  129. package/docs/integrations/matomo-analytics.md +256 -111
  130. package/docs/integrations/meta-pixel.md +197 -324
  131. package/docs/integrations/microsoft-clarity.md +233 -114
  132. package/docs/integrations/microsoft-uet.md +245 -110
  133. package/docs/integrations/mixpanel-analytics.md +252 -87
  134. package/docs/integrations/openai-pixel.md +441 -0
  135. package/docs/integrations/overview.md +95 -133
  136. package/docs/integrations/pirsch.md +249 -96
  137. package/docs/integrations/plausible-analytics.md +241 -100
  138. package/docs/integrations/posthog.md +353 -214
  139. package/docs/integrations/promptwatch.md +251 -81
  140. package/docs/integrations/reddit-pixel.md +226 -173
  141. package/docs/integrations/rudderstack.md +244 -187
  142. package/docs/integrations/rybbit-analytics.md +244 -91
  143. package/docs/integrations/segment.md +238 -92
  144. package/docs/integrations/snapchat-pixel.md +240 -110
  145. package/docs/integrations/tiktok-pixel.md +249 -81
  146. package/docs/integrations/umami-analytics.md +242 -95
  147. package/docs/integrations/vercel-analytics.md +242 -90
  148. package/docs/integrations/x-pixel.md +238 -104
  149. package/docs/integrations/youtube.md +354 -142
  150. package/docs/upgrade-v3.md +334 -0
  151. package/package.json +85 -78
  152. package/readme.json +2 -2
  153. package/dist/e2e-test-utils.cjs +0 -166
  154. package/dist/engine/compile.cjs +0 -130
  155. package/dist/engine/runtime.cjs +0 -475
  156. package/dist/registry.cjs +0 -423
  157. package/dist/resolve.cjs +0 -71
  158. package/dist/types.cjs +0 -69
  159. package/dist/vendors/_shared/attributes.cjs +0 -55
  160. package/dist/vendors/_shared/google-consent.cjs +0 -69
  161. package/dist/vendors/_shared/install-builders.cjs +0 -59
  162. package/dist/vendors/_shared/script-url.cjs +0 -78
  163. package/dist/vendors/ads-and-pixels/linkedin-insights.cjs +0 -89
  164. package/dist/vendors/ads-and-pixels/meta-pixel.cjs +0 -206
  165. package/dist/vendors/ads-and-pixels/microsoft-uet.cjs +0 -151
  166. package/dist/vendors/ads-and-pixels/reddit-pixel.cjs +0 -151
  167. package/dist/vendors/ads-and-pixels/snapchat-pixel.cjs +0 -131
  168. package/dist/vendors/ads-and-pixels/tiktok-pixel.cjs +0 -130
  169. package/dist/vendors/ads-and-pixels/x-pixel.cjs +0 -92
  170. package/dist/vendors/analytics/adobe-analytics.cjs +0 -90
  171. package/dist/vendors/analytics/ahrefs-analytics.cjs +0 -68
  172. package/dist/vendors/analytics/amplitude.cjs +0 -193
  173. package/dist/vendors/analytics/clearbit.cjs +0 -69
  174. package/dist/vendors/analytics/cloudflare-web-analytics.cjs +0 -73
  175. package/dist/vendors/analytics/databuddy.cjs +0 -144
  176. package/dist/vendors/analytics/fathom-analytics.cjs +0 -76
  177. package/dist/vendors/analytics/google-tag.cjs +0 -107
  178. package/dist/vendors/analytics/heap.cjs +0 -181
  179. package/dist/vendors/analytics/hightouch.cjs +0 -153
  180. package/dist/vendors/analytics/hotjar.cjs +0 -85
  181. package/dist/vendors/analytics/logrocket.cjs +0 -99
  182. package/dist/vendors/analytics/matomo-analytics.cjs +0 -232
  183. package/dist/vendors/analytics/microsoft-clarity.cjs +0 -138
  184. package/dist/vendors/analytics/mixpanel-analytics.cjs +0 -134
  185. package/dist/vendors/analytics/pirsch.cjs +0 -108
  186. package/dist/vendors/analytics/plausible-analytics.cjs +0 -122
  187. package/dist/vendors/analytics/posthog.cjs +0 -236
  188. package/dist/vendors/analytics/promptwatch.cjs +0 -70
  189. package/dist/vendors/analytics/rudderstack.cjs +0 -227
  190. package/dist/vendors/analytics/rybbit-analytics.cjs +0 -104
  191. package/dist/vendors/analytics/segment.cjs +0 -97
  192. package/dist/vendors/analytics/umami-analytics.cjs +0 -80
  193. package/dist/vendors/analytics/vercel-analytics.cjs +0 -94
  194. package/dist/vendors/functional/crisp.cjs +0 -143
  195. package/dist/vendors/functional/intercom.cjs +0 -89
  196. package/dist/vendors/tag-managers/google-tag-manager.cjs +0 -100
  197. package/docs/shared/react/guides/script-loader.md +0 -311
@@ -1,501 +1,168 @@
1
1
  ---
2
- title: Script Loader
3
- description: Gate third-party scripts behind consent in Next.js load Google
4
- Analytics, Meta Pixel, and other tracking scripts only when users grant
5
- permission.
2
+ title: Load scripts with consent
3
+ description: Register vendor scripts in your existing Next.js ConsentRoot and
4
+ handle loading and revocation.
6
5
  group: frameworks
7
6
  ---
8
- The script loader manages third-party JavaScript based on consent state. You declare scripts in your provider's `scripts` option, and c15t decides when each script should load, stay loaded, unload, or receive a consent update.
9
7
 
10
- Use it for analytics, pixels, tag managers, product analytics, and other vendor snippets that should not run until the right consent condition is satisfied. Prebuilt helpers live in [`@c15t/scripts`](/docs/integrations/overview); custom scripts can be declared directly when the vendor is specific to your app.
11
-
12
- <PackageCommandTabs mode="install" command="@c15t/scripts" />
13
-
14
- > ℹ️ **Info:**
15
- > Start with the integrations overview before writing your own script. Built-in helpers encode vendor boot order, consent updates, and common defaults so you do not have to.
16
- >
17
- > 📝 **Note:**
18
- > If you need a vendor c15t does not ship yet, see the custom integration guide. It explains when a one-off Script is enough and when to build a reusable manifest-backed helper.
19
- >
20
- > ℹ️ **Info:**
21
- > The script loader handles JavaScript tags and callback lifecycles. For iframe-only embeds, use the iframe blocking pattern. For UI components such as maps or video players, combine consent state with a component-level placeholder or a dedicated renderable integration.
22
-
23
- ## Basic Usage
24
-
25
- Pass an array of scripts to `ConsentManagerProvider`. Built-in helpers from `@c15t/scripts` return plain `Script` objects, so they sit beside app-specific scripts:
26
-
27
- ```tsx
28
- import { type ReactNode } from 'react';
29
- import { ConsentManagerProvider } from '@c15t/nextjs';
30
- import { metaPixel } from '@c15t/scripts/meta-pixel';
8
+ ## Keep one owner for vendor scripts
9
+
10
+ The [App Router](https://c15t.com/docs/frameworks/next/app-router) and
11
+ [Pages Router](https://c15t.com/docs/frameworks/next/pages-router) setups already register scripts
12
+ in a client wrapper. Keep that wrapper and add vendors to `lib/scripts.ts`.
13
+ If you are adding scripts to an existing c15t setup, install the helpers and
14
+ use the same registration pattern below.
15
+
16
+ | Package manager | Command |
17
+ | :-------------- | :-------------------------- |
18
+ | npm | `npm install @c15t/scripts` |
19
+ | pnpm | `pnpm add @c15t/scripts` |
20
+ | yarn | `yarn add @c15t/scripts` |
21
+ | bun | `bun add @c15t/scripts` |
22
+
23
+ Keep `c15t.config.ts` and the manifest route from your router setup. These shared
24
+ URLs connect initialization and consent submissions to the same backend.
25
+
26
+ ## Register scripts in a client wrapper
27
+
28
+ The [runnable Next.js example](https://c15t.com/docs/examples) uses PostHog for measurement and
29
+ X Pixel for marketing. Set `NEXT_PUBLIC_POSTHOG_KEY` and
30
+ `NEXT_PUBLIC_X_PIXEL_ID` to your own project identifiers before building.
31
+ `NEXT_PUBLIC_POSTHOG_HOST` optionally selects your PostHog region's API host.
32
+ Omit a vendor's ID to leave that integration disabled, or replace its helper
33
+ with the [integration](../../integrations/overview.md) your application uses. Include the
34
+ measurement and marketing categories in your policy for these two vendors.
35
+
36
+ Create `lib/scripts.ts` with the example's script configuration:
37
+
38
+ ```ts title="lib/scripts.ts"
39
+ import { posthog } from '@c15t/scripts/posthog';
40
+ import { xPixel } from '@c15t/scripts/x-pixel';
41
+ import type { Script } from 'c15t';
42
+
43
+ export const posthogConfigured = Boolean(process.env.NEXT_PUBLIC_POSTHOG_KEY);
44
+ export const xPixelConfigured = Boolean(process.env.NEXT_PUBLIC_X_PIXEL_ID);
45
+
46
+ export const scripts: Script[] = [];
47
+
48
+ if (process.env.NEXT_PUBLIC_POSTHOG_KEY) {
49
+ scripts.push(
50
+ posthog({
51
+ apiHost: process.env.NEXT_PUBLIC_POSTHOG_HOST,
52
+ id: process.env.NEXT_PUBLIC_POSTHOG_KEY,
53
+ initOptions: { cookieless_mode: 'never' },
54
+ loadMode: 'after-consent',
55
+ })
56
+ );
57
+ }
31
58
 
32
- export function ConsentManager({ children }: { children: ReactNode }) {
33
- return (
34
- <ConsentManagerProvider
35
- options={{
36
- mode: 'hosted',
37
- backendURL: '/api/c15t',
38
- scripts: [
39
- metaPixel({ pixelId: '123456' }),
40
- {
41
- id: 'custom-analytics',
42
- src: 'https://cdn.example.com/analytics.js',
43
- category: 'measurement',
44
- },
45
- ],
46
- }}
47
- >
48
- {children}
49
- </ConsentManagerProvider>
50
- );
59
+ if (process.env.NEXT_PUBLIC_X_PIXEL_ID) {
60
+ scripts.push(xPixel({ pixelId: process.env.NEXT_PUBLIC_X_PIXEL_ID }));
51
61
  }
52
62
  ```
53
63
 
54
- The script loader runs in the browser, so place the provider in the client boundary that owns your consent UI and pass scripts through the provider options instead of injecting them in Server Components.
64
+ PostHog waits for measurement consent here. `cookieless_mode: 'never'` disables
65
+ cookieless capture after rejection. X Pixel waits for marketing consent. Remove
66
+ any existing loader for these vendors, including `next/script` and tag-manager
67
+ entries, so each integration loads once.
55
68
 
56
- ## Recommended Structure
69
+ Create this client wrapper. It keeps scripts and browser callbacks in the client
70
+ while the router supplies the visitor's resolved state through `state`:
57
71
 
58
- Define your script list once and keep it next to the consent provider:
59
-
60
- ```tsx
72
+ ```tsx title="components/consent.tsx"
61
73
  'use client';
62
74
 
63
- import { type ReactNode } from 'react';
64
- import { ConsentManagerProvider } from '@c15t/nextjs';
65
- import { gtag } from '@c15t/scripts/google-tag';
66
- import { metaPixel } from '@c15t/scripts/meta-pixel';
67
-
68
- const scripts = [
69
- gtag({ id: 'G-XXXXXXX' }),
70
- metaPixel({ pixelId: '123456' }),
71
- ];
72
-
73
- export function ConsentProvider({ children }: { children: ReactNode }) {
75
+ import type { ReactNode } from 'react';
76
+ import {
77
+ ConsentBanner,
78
+ ConsentDialog,
79
+ ConsentDialogLink,
80
+ ConsentRoot,
81
+ } from 'c15t/next';
82
+ import type { ConsentRootProps } from 'c15t/next';
83
+ import { consentConfig } from '../c15t.config';
84
+ import { scripts } from '../lib/scripts';
85
+
86
+ export function Consent({
87
+ children,
88
+ state,
89
+ }: {
90
+ children: ReactNode;
91
+ state: ConsentRootProps['state'];
92
+ }) {
74
93
  return (
75
- <ConsentManagerProvider
76
- options={{
77
- mode: 'hosted',
78
- backendURL: '/api/c15t',
79
- scripts,
80
- }}
81
- >
94
+ <ConsentRoot state={state} config={consentConfig} scripts={scripts}>
82
95
  {children}
83
- </ConsentManagerProvider>
96
+ <ConsentBanner />
97
+ <ConsentDialog />
98
+ <footer>
99
+ <ConsentDialogLink>Privacy settings</ConsentDialogLink>
100
+ </footer>
101
+ </ConsentRoot>
84
102
  );
85
103
  }
86
104
  ```
87
105
 
88
- Use environment variables or server-rendered configuration to choose ids per environment, but avoid rendering vendor scripts with `next/script` separately that bypasses c15t's lifecycle for that vendor.
89
-
90
- ## Mental Model
91
-
92
- Every script you register has the same lifecycle. c15t evaluates each script against the current consent state, then drives it through a small number of states:
93
-
94
- 1. **Pending** — registered but waiting for consent. Nothing is in the DOM yet.
95
- 2. **Loaded** — consent matched, c15t injected the script (or ran callbacks for callback-only scripts).
96
- 3. **Updated** — already loaded, consent state changed, `onConsentChange` ran so the SDK can react.
97
- 4. **Unloaded** — consent was revoked. c15t removed the script element unless you opted into persistence.
98
-
99
- Four lifecycle callbacks let you hook into transitions: `onBeforeLoad`, `onLoad`, `onConsentChange`, and `onError`. Two flags — [`alwaysLoad`](#always-load) and [`persistAfterConsentRevoked`](#persist-after-revocation) — change how c15t treats consent boundaries. Everything else (DOM placement, ad-block evasion, dynamic management) is a refinement on top of this core model.
100
-
101
- ## Choose the Right Approach
102
-
103
- Most projects mix more than one style. Pick the smallest one that keeps consent behavior obvious:
104
-
105
- |Style|Use when|
106
- |--|--|
107
- |**Built-in helper** from `@c15t/scripts`|c15t already ships the vendor. See the [integrations overview](/docs/integrations/overview).|
108
- |**Plain `Script`**|One-off app code with simple load and callback behavior.|
109
- |**Callback-only `Script`**|Another package already loaded the SDK; c15t only synchronizes consent.|
110
- |**Manifest-backed helper**|Reusable vendor integration with structured setup phases, queues, stubs, or a vendor consent API.|
111
- |**Iframe / renderable integration**|Vendor exposes an iframe or React component, not just a `<script>` tag.|
112
-
113
- ## Script Types
114
-
115
- ### Standard Scripts
116
-
117
- Standard scripts load an external JavaScript file via a `<script>` tag. This is the default for most analytics and pixel SDKs:
118
-
119
- ```tsx
120
- {
121
- id: 'analytics',
122
- src: 'https://cdn.example.com/analytics.js',
123
- category: 'measurement',
124
- }
125
- ```
126
-
127
- ### Inline Scripts
128
-
129
- Inline scripts execute JavaScript from `textContent` instead of loading a URL. Use these sparingly; a manifest-backed helper is usually better for reusable vendor code.
130
-
131
- ```tsx
132
- {
133
- id: 'gtag-config',
134
- textContent: `
135
- window.dataLayer = window.dataLayer || [];
136
- function gtag(){dataLayer.push(arguments);}
137
- gtag('js', new Date());
138
- gtag('config', 'G-XXXXXX');
139
- `,
140
- category: 'measurement',
141
- }
142
- ```
143
-
144
- ### Callback-Only Scripts
145
-
146
- Callback-only scripts do not inject a script tag. They run lifecycle callbacks when consent allows them to. Use this when another package has already loaded the SDK and c15t only needs to drive consent:
147
-
148
- ```tsx
149
- {
150
- id: 'posthog-consent',
151
- callbackOnly: true,
152
- category: 'measurement',
153
- onLoad: ({ hasConsent }) => {
154
- if (hasConsent) {
155
- posthog.opt_in_capturing();
156
- }
157
- },
158
- onConsentChange: ({ hasConsent }) => {
159
- if (hasConsent) {
160
- posthog.opt_in_capturing();
161
- } else {
162
- posthog.opt_out_capturing();
163
- }
164
- },
165
- }
166
- ```
167
-
168
- ### Manifest-Backed Helpers
169
-
170
- Built-in integrations in `@c15t/scripts` are manifest-backed. A manifest describes vendor setup as structured phases, then c15t compiles it into a `Script`. Manifests keep queue stubs, script URLs, consent signaling, and post-load work consistent across apps and they are safe to ship from a server.
171
-
172
- Use a manifest-backed helper when:
173
-
174
- * the integration should be reused across projects,
175
- * the vendor snippet has ordered setup steps,
176
- * the vendor exposes a consent API,
177
- * or you plan to contribute the integration back to c15t.
178
-
179
- Read the [custom integration guide](/docs/integrations/building-integrations) for the manifest contract, phases, and testing checklist.
180
-
181
- ### Iframe And Renderable Integrations
182
-
183
- Some vendors are not just script tags. YouTube embeds, maps, calendars, and checkout widgets often need a visible component, a placeholder, or an iframe.
184
-
185
- * For iframe-only embeds, gate the iframe `src` with the [iframe blocking](/docs/frameworks/react/iframe-blocking) pattern instead of loading a script just to hide an iframe.
186
- * For SDK-backed UI, use the script loader for the shared SDK and render the component only when consent and SDK readiness agree.
187
- * Use `YouTubeEmbed` for the iframe-only YouTube candidate and `GoogleMap` for the callback-based SDK candidate.
188
- * Use `useConsentScript()` when building custom wrappers. It registers scripts through the consent store, follows `loadedScripts`, and returns a promise-shaped readiness contract for callback-based SDKs.
189
-
190
- ## Lifecycle Callbacks
191
-
192
- Every script supports four callbacks. Each receives a `ScriptCallbackInfo` payload (id, element, hasConsent, consents):
193
-
194
- * `onBeforeLoad` — runs before the script tag is injected. Create globals, queues, or vendor stubs here.
195
- * `onLoad` — runs after the browser loads the script. Call vendor `init()` APIs here.
196
- * `onConsentChange` — runs for loaded scripts when consent changes. Forward the new consent state to the vendor SDK.
197
- * `onError` — runs when the script fails to load. Record diagnostics or render a fallback.
198
-
199
- ```tsx
200
- {
201
- id: 'analytics',
202
- src: 'https://analytics.example.com/v2.js',
203
- category: 'measurement',
204
- onBeforeLoad: ({ id }) => {
205
- window.analyticsQueue = window.analyticsQueue || [];
206
- },
207
- onLoad: () => {
208
- window.analytics.init('my-key');
209
- },
210
- onError: ({ error }) => {
211
- console.error('Failed to load analytics:', error);
212
- },
213
- onConsentChange: ({ hasConsent }) => {
214
- window.analytics.setConsent(hasConsent);
215
- },
216
- }
217
- ```
218
-
219
- ## Consent Conditions
220
-
221
- The `category` field accepts a `HasCondition`. It can be a single consent category or a logical expression:
222
-
223
- ```tsx
224
- // Simple: requires measurement consent
225
- { category: 'measurement' }
226
-
227
- // AND: requires both measurement and marketing
228
- { category: { and: ['measurement', 'marketing'] } }
229
-
230
- // OR: requires either measurement or marketing
231
- { category: { or: ['measurement', 'marketing'] } }
232
- ```
233
-
234
- Consent categories use the same names as the rest of c15t (`necessary`, `functionality`, `experience`, `measurement`, `marketing`).
235
-
236
- ## Persistence Options
237
-
238
- ### Always Load
239
-
240
- `alwaysLoad` loads the script regardless of whether its category is currently granted. Use it only when the vendor must be present early **and** has a reliable consent API of its own — Google Tag Manager with Consent Mode is the canonical example.
241
-
242
- ```tsx
243
- {
244
- id: 'google-tag-manager',
245
- src: 'https://www.googletagmanager.com/gtm.js?id=GTM-XXXX',
246
- category: 'measurement',
247
- alwaysLoad: true,
248
- }
249
- ```
250
-
251
- When `alwaysLoad` is on, `onConsentChange` becomes mandatory: it is how the loaded SDK learns about every transition.
252
-
253
- > ⚠️ **Warning:**
254
- > alwaysLoad shifts compliance responsibility to the vendor integration. Make sure the script receives denied-by-default consent signals before it can track.
255
-
256
- ### Persist After Revocation
257
-
258
- `persistAfterConsentRevoked` keeps a script in the page after consent is revoked instead of unloading it. Use it only when the vendor exposes a runtime consent toggle — otherwise unloading is safer because removing the element guarantees the SDK stops.
259
-
260
- ```tsx
261
- {
262
- id: 'error-tracking',
263
- src: 'https://errors.example.com/track.js',
264
- category: 'measurement',
265
- persistAfterConsentRevoked: true,
266
- onConsentChange: ({ hasConsent }) => {
267
- window.ErrorTracker.setConsent(hasConsent);
268
- },
269
- }
270
- ```
271
-
272
- As with `alwaysLoad`, `onConsentChange` is how the persisted SDK learns about consent updates.
273
-
274
- ### `alwaysLoad` vs `persistAfterConsentRevoked`
275
-
276
- These two flags answer different questions. Use this table to keep them straight:
106
+ `ConsentRoot` already provides the consent runtime. Mount this wrapper once;
107
+ do not add a second provider. Keep your site's content and footer inside it.
277
108
 
278
- |Question|`alwaysLoad`|`persistAfterConsentRevoked`|
279
- |--|--|--|
280
- |Loads before consent is granted?|Yes|No (waits for consent like a normal script)|
281
- |Stays loaded after consent is revoked?|Yes|Yes|
282
- |Requires a vendor consent API?|Yes|Yes|
109
+ ## Pass prepared consent through your router
283
110
 
284
- ## DOM Placement
285
-
286
- Control where the script is injected and whether the element id is anonymized:
111
+ App Router awaits the prefetch in the `ResolvedConsent` Server Component from
112
+ the [App Router guide](https://c15t.com/docs/frameworks/next/app-router) and renders the
113
+ wrapper inside it. This partial example is that component; keep the
114
+ `Suspense` boundary, `html`, `body` and stylesheet from your existing layout:
287
115
 
288
116
  ```tsx
289
- {
290
- id: 'widget',
291
- src: 'https://widget.example.com/embed.js',
292
- category: 'experience',
293
- target: 'body', // 'head' (default) or 'body'
294
- anonymizeId: true, // default: true, hides the c15t script id from ad blockers
295
- nonce: 'abc123', // optional CSP nonce
117
+ import type { ReactNode } from 'react';
118
+ import { resolveConsent } from 'c15t/next/server';
119
+ import { consentConfig } from '../c15t.config';
120
+ import { Consent } from '../components/consent';
121
+
122
+ async function ResolvedConsent({ children }: { children: ReactNode }) {
123
+ const state = await resolveConsent({ config: consentConfig });
124
+ return <Consent state={state}>{children}</Consent>;
296
125
  }
297
126
  ```
298
127
 
299
- Set `anonymizeId: false` only when another script or test needs a stable DOM id. Pass `nonce` when your CSP requires it; c15t applies it directly to the generated `<script>` element.
300
-
301
- You usually do not need a per-script `nonce`. Setting `nonce` once on the provider covers every injected script (and the theme stylesheet); a per-script value overrides it for that script alone.
302
-
303
- ## Dynamic Management
304
-
305
- Framework packages expose script-manager methods so integrations can be added, removed, or inspected at runtime. Use this for tenant-specific tools, feature-flagged scripts, or vendors that are configured after sign-in:
306
-
307
- * `setScripts(scripts)` — registers script definitions and immediately evaluates them against consent.
308
- * `removeScript(id)` — removes a definition and unloads its element if needed.
309
- * `isScriptLoaded(id)` — returns whether c15t has loaded a script.
310
- * `getLoadedScriptIds()` — returns every currently loaded script id.
311
-
312
- Dynamic scripts should still use stable ids. If the same vendor is added repeatedly with different ids, c15t treats each call as a new script.
313
-
314
- ## Calling Vendor APIs From Your App
315
-
316
- The script loader controls **when the vendor SDK loads**. It does not intercept calls your application code makes to that SDK afterwards. Whether your event calls are safe before consent is granted depends on the script's persistence flags:
317
-
318
- |Vendor pattern|What c15t does|What your app code must do|
319
- |--|--|--|
320
- |Consent-gated load, unloaded on revoke (e.g. cookieless analytics)|Script not in DOM until consent granted; removed on revoke. Global is `undefined` outside that window.|**Guard every call.** Unguarded `window.vendor.track(...)` throws when the global is absent.|
321
- |Consent-gated load with `persistAfterConsentRevoked` (e.g. Meta Pixel)|Script not in DOM until consent granted; stays after revoke. c15t calls vendor's consent-revoke API on revocation.|Guard calls only for the pre-initial-consent window. Once loaded, the SDK handles its own suppression.|
322
- |`alwaysLoad: true` with a vendor consent API (e.g. GTM, gtag, Databuddy, PostHog)|Script in DOM on page start; c15t signals consent state through the vendor's API.|Calls are safe — the vendor SDK suppresses transmission when consent is denied.|
323
- |No app-facing API (e.g. Cloudflare Web Analytics)|Script in/out of DOM based on consent. Tracking is fully automatic.|Nothing to guard.|
324
-
325
- The safe pattern in React is to read consent state through `useConsentManager().has(category)` before calling the SDK:
326
-
327
- ```tsx
328
- import { useCallback } from 'react';
329
- import { useConsentManager } from '@c15t/react';
330
-
331
- function useTrackSignup() {
332
- const { has } = useConsentManager();
333
-
334
- return useCallback(() => {
335
- if (has('measurement')) {
336
- window.fathom?.trackEvent('signup');
337
- }
338
- }, [has]);
339
- }
340
-
341
- function SignupButton() {
342
- const trackSignup = useTrackSignup();
343
-
344
- return <button onClick={trackSignup}>Sign up</button>;
345
- }
346
- ```
347
-
348
- From non-React code, read the consent store directly:
349
-
350
- ```ts
351
- import { getOrCreateConsentRuntime } from 'c15t';
352
-
353
- const { consentStore } = getOrCreateConsentRuntime();
354
-
355
- if (consentStore.getState().has('measurement')) {
356
- window.fathom?.trackEvent('signup');
357
- }
358
- ```
359
-
360
- Each [integration page](/docs/integrations/overview) includes a vendor-specific **Tracking events in your app** block that names which pattern applies.
361
-
362
- ## Debugging Checklist
363
-
364
- When a script does not behave as expected:
365
-
366
- 1. Confirm the script's `category` matches the consent that has been granted.
367
- 2. Check whether the script is `alwaysLoad` or consent-gated.
368
- 3. Confirm `onBeforeLoad` creates any globals before the vendor code reads them.
369
- 4. Confirm `onConsentChange` updates persisted or always-loaded scripts when consent changes.
370
- 5. Check whether the browser or an ad blocker blocked the request.
371
- 6. Use c15t devtools to inspect script lifecycle events when available.
372
-
373
- ## Dynamic Script Management
374
-
375
- The shared guide above lists what the script-manager methods do. In Next.js they are exposed through `useConsentManager()`:
376
-
377
- ```tsx
378
- import { useConsentManager } from '@c15t/nextjs';
379
-
380
- function ScriptManager() {
381
- const {
382
- setScripts,
383
- removeScript,
384
- isScriptLoaded,
385
- getLoadedScriptIds,
386
- } = useConsentManager();
387
-
388
- // ...
389
- }
390
- ```
391
-
392
- Register dynamic scripts from a client effect or event handler — never directly in the render body — so React can run the call once per dependency change and tear it down on unmount:
393
-
394
- ```tsx
395
- 'use client';
396
-
397
- import { useEffect } from 'react';
398
- import { useConsentManager } from '@c15t/nextjs';
399
-
400
- export function WorkspaceAnalytics({ workspaceId }: { workspaceId: string }) {
401
- const { setScripts, removeScript } = useConsentManager();
402
-
403
- useEffect(() => {
404
- const scriptId = `workspace-analytics-${workspaceId}`;
405
-
406
- setScripts([
407
- {
408
- id: scriptId,
409
- src: `https://cdn.example.com/workspaces/${workspaceId}.js`,
410
- category: 'measurement',
411
- },
412
- ]);
413
-
414
- return () => {
415
- removeScript(scriptId);
416
- };
417
- }, [workspaceId, setScripts, removeScript]);
418
-
419
- return null;
420
- }
421
- ```
422
-
423
- ## Renderable Integrations
424
-
425
- Some integrations need a visible component, not just a script tag. Google Maps, YouTube, checkout widgets, and calendars all need consent gating plus component lifecycle.
426
-
427
- Use the [Google Maps](/docs/integrations/google-maps) and
428
- [YouTube](/docs/integrations/youtube) renderable integrations through
429
- `@c15t/nextjs` in client components:
430
-
431
- ```tsx
432
- 'use client';
433
-
434
- import { GoogleMap, YouTubeEmbed } from '@c15t/nextjs';
435
-
436
- export function ConsentAwareMedia() {
437
- const googleMapsApiKey = process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY;
438
-
439
- return (
440
- <>
441
- {googleMapsApiKey && (
442
- <GoogleMap
443
- apiKey={googleMapsApiKey}
444
- authReferrerPolicy="origin"
445
- center={{ lat: 40.7128, lng: -74.006 }}
446
- className="overflow-hidden rounded-xl"
447
- consentCategory="measurement"
448
- zoom={12}
449
- />
450
- )}
451
-
452
- <YouTubeEmbed
453
- consentCategory="marketing"
454
- title="Product demo"
455
- videoId="dQw4w9WgXcQ"
456
- />
457
- </>
458
- );
459
- }
460
- ```
461
-
462
- The implementation splits the problem into three layers:
463
-
464
- 1. Use the script loader as the source of truth for shared SDK loading.
465
- 2. Use `useConsentScript()` for SDK readiness when a vendor uses a callback-style loader.
466
- 3. Create the widget instance only on the client and clean it up on unmount.
467
-
468
- Google Maps is SDK-backed and uses one shared c15t-managed script plus per-component map instances. The script is never requested before consent. Once loaded, its manager registration is retained to respect Google's one-loader-per-page constraint, while each map instance is destroyed on unmount or when consent becomes unavailable. The component adopts an existing Google Maps global, has a visible `320px` default height, uses the official API types, and reports loader, authentication, and constructor failures through `onError` and `errorFallback`.
128
+ To stream the page shell before consent resolves instead, pass the unawaited
129
+ promise from a synchronous layout as described in
130
+ [stream the page while consent resolves](https://c15t.com/docs/frameworks/next/app-router#stream-the-page-while-consent-resolves).
469
131
 
470
- All maps with the same `scriptId` must use the same loader configuration. `mapId` changes recreate the instance; `center`, `zoom`, and updateable `options` update it in place. You can pass Google's direct-loader options through `libraries`, `language`, `region`, `version`, `authReferrerPolicy`, `mapIds`, `channel`, and `solutionChannel`.
132
+ Pages Router passes `state={pageProps.consentState ?? {}}` to this wrapper
133
+ in `_app.tsx`. Keep `getServerSideProps` and its `c15t/next/pages` helper.
134
+ The router guides contain complete layout and `_app.tsx` files.
471
135
 
472
- YouTube is iframe-only and uses the existing `Frame` boundary rather than the
473
- YouTube iframe API. It defaults to a responsive, borderless 16:9 frame with a
474
- localized loading state, stable placeholder dimensions, native lazy loading,
475
- and the privacy-enhanced host. Its `className` and forwarded ref target the
476
- iframe; `wrapperClassName` and `frameProps` target the `Frame`. Boolean `params`
477
- become `1` or `0`.
136
+ For static export or browser-only initialization, pass `state={{}}` and keep
137
+ that setup's existing transport. Register scripts on its existing `ConsentRoot`;
138
+ do not introduce server prefetch or local routes just to add a vendor.
478
139
 
479
- For a custom client-side SDK, `useConsentScript()` exposes `blocked`, `loading`,
480
- `ready`, and `error` states plus `readyValue`, `error`, and `ready`. Change its
481
- `retryKey` after a failed attempt to retry the same script id. Registrations
482
- with one id must use compatible script and readiness options; conflicts surface
483
- as `ConsentScriptConflictError`.
140
+ ## Check each vendor's loading behavior
484
141
 
485
- For iframe-only embeds, use the [iframe blocking](/docs/frameworks/next/iframe-blocking) pattern or `YouTubeEmbed`. For SDK-backed widgets, load the SDK once and let each component instance create and clean up its own widget. Avoid mixing `next/script` with c15t for the same vendor.
142
+ The example explicitly configures PostHog to load after consent and disables
143
+ cookieless capture. Those settings are deliberate; its default helper can load
144
+ before consent and use the SDK's consent controls. Read the
145
+ [PostHog guide](../../integrations/posthog.md) before changing them.
486
146
 
487
- ## App Router Notes
147
+ Ordinary scripts wait for their category's effective permission. Give each
148
+ script a stable unique `id` and remove any other loader for the same vendor.
149
+ Helpers with `alwaysLoad` may load an SDK before permission is granted; a
150
+ category field alone does not guarantee no requests. See the
151
+ [vendor guides](../../integrations/overview.md) for their exact contracts.
488
152
 
489
- * The provider and any component that calls `useConsentManager()` must be client components.
490
- * Keep vendor ids out of static examples when they differ per environment — read them from `process.env.NEXT_PUBLIC_*` or runtime config.
491
- * If a script must be available before a page becomes interactive, prefer a built-in helper that models denied-consent defaults rather than adding a separate `next/script` tag.
492
- * If you use CSP nonces, set `nonce` on the provider options so c15t applies it to every injected script element and the theme stylesheet. See [Content Security Policy](/docs/frameworks/next/components/consent-manager-provider#content-security-policy) for reading the nonce in the App Router.
153
+ Removing a script element cannot undo executed JavaScript or requests already
154
+ sent. PostHog exposes capture controls; X Pixel has no consent-update API.
155
+ Stop future event calls after revocation and test a change from allowed to
156
+ denied, as well as initial denial.
493
157
 
494
- ## API Reference
158
+ ## Verify the integration
495
159
 
496
- |Property|Value|
497
- |:--|:--|
498
- |Type Name|\`Script\`|
499
- |Source Path|\`./packages/core/src/libs/script-loader/types.ts\`|
160
+ With an opt-in policy and no saved choice, neither configured example vendor
161
+ should load. Allow measurement only: PostHog loads and X Pixel remains blocked.
162
+ Reject, reload, and reopen Privacy settings to confirm the choice persists.
500
163
 
501
- \*ExtractedTypeTable: Could not extract "Script" from "./packages/core/src/libs/script-loader/types.ts" using base path "/home/runner/work/c15t/c15t". Verify the path/name and that the file is included by your tsconfig.\*
164
+ Use the [runnable example](https://c15t.com/docs/examples) to inspect the same script definitions
165
+ with DevTools, or follow [verification](../../guides/verify-consent.md) in your app.
166
+ Use [custom integrations](../../integrations/building-integrations.md) for an
167
+ unlisted vendor. Google helpers have a separate
168
+ [Consent Mode contract](../../integrations/google-tag-manager.md).