Communitygithub.com

setup-consent

Add cookie consent to a website or web app with @turbo-labs/consent (github.com/turbo-labs/consent) — the config, the region route, the banner in the site's own look, and every tracker and third-party widget gated behind it (GTM, PostHog, support chat, …), plus the test and screenshot fixes it needs. Use when the user asks for a cookie banner, cookie consent, GDPR consent, consent mode, or to gate analytics; or wants a second site to share an existing site's consent.

setup-consent 是什麼?

setup-consent is a Claude Code agent skill that add cookie consent to a website or web app with @turbo-labs/consent (github.com/turbo-labs/consent) — the config, the region route, the banner in the site's own look, and every tracker and third-party widget gated behind it (GTM, PostHog, support chat, …), plus the test and screenshot fixes it needs. Use when the user asks for a cookie banner, cookie consent, GDPR consent, consent mode, or to gate analytics; or wants a second site to share an existing site's consent.

相容平台✓Claude Code~Codex CLI~Cursor
npx skills add https://github.com/turbo-labs/consent/tree/HEAD/skills/setup-consent

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

Set up @turbo-labs/consent

The package holds the rules (who is asked, the cookie, Global Privacy Control, Consent Mode, withdrawal). Your job is the integration: a config, a region route, a banner that looks like the site, and every tracker gated — the step that gets missed. The README is the API reference; read it alongside this.

Work through the steps in order. Stop and ask the user at each Decide — those answers change the code.

1. Inventory what sets cookies or calls third parties

Before writing anything, list every tracker and widget, with where it starts:

  • Search for: googletagmanager, gtag, dataLayer, posthog, mixpanel, segment, amplitude, hotjar, clarity, plausible, intercom, crisp, featurebase, hubspot, fbq, linkedin, <Script, <script src=, instrumentation-client, .init(.
  • Read the site's CSP (next.config.*, headers config): every third-party origin in script-src/connect-src/frame-src is a lead.
  • Note how each starts: an inline snippet in the layout, a module-scope init, a provider component, a tag inside the GTM container.

Decide with the user which category each belongs to. Typical: analytics (GA4, PostHog, product analytics), marketing (ad pixels, ad conversions — mark saleOrShare: true), functional (support chat, feedback widgets). Only create categories something actually uses: a site with no ads needs no marketing category, and then Consent Mode's ad signals simply stay denied. Strictly necessary cookies (session, the consent cookie itself) are never a category.

2. Install

npm install github:turbo-labs/consent#<latest tag>   # gh api repos/turbo-labs/consent/tags --jq '.[0].name'

Check the lockfile diff is only the new package. If npm stripped fields such as "libc" from unrelated entries, the lockfile was written by a newer npm: revert it and reinstall with that version (npx -y npm@11 install …).

3. Write the config, once per app

src/lib/consent.ts (or the project's equivalent), imported everywhere — never two stores on one page:

import { defineConsent } from "@turbo-labs/consent"

export const consent = defineConsent({
  cookie: { name: "acme_consent", domain: ".acme.com" },
  version: 1,
  eventPrefix: "acme",
  region: {
    lookup: async () => {
      const response = await fetch("/api/region", { cache: "no-store" })
      if (!response.ok) throw new Error(`region lookup failed: ${response.status}`)
      return ((await response.json()) as { country?: string | null }).country ?? null
    },
  },
  categories: [/* from step 1 */],
})
  • Several apps on one domain (marketing site + app): one cookie on the shared parent domain, and the same cookie name, version, category keys and region in every app — or each reads the other's choice as no choice. Put a "keep in step with …" comment in each file and a test in each app that pins those values (labels and descriptions may differ).
  • Existing consent code? Keep its cookie name and pass a legacy reader so nobody is asked again (built-ins and factories are in the README).
  • Fill clear for each category with the cookie and localStorage prefixes its tools write (_ga, _gid, _gat, ph_, __ph, …) so a withdrawal really deletes them.
  • Decide whether to gate by region (the default above: ask only the EEA, UK and Switzerland, everyone else starts on) or ask everyone (omit region).
  • Use no path aliases (@/…) in this file if test or screenshot scripts will import it.

4. The region route

// app/api/region/route.ts (Next.js; same idea elsewhere)
import { countryFromHeaders } from "@turbo-labs/consent/server"
export const dynamic = "force-dynamic"
export const GET = (request: Request) =>
  Response.json({ country: countryFromHeaders(request.headers) }, { headers: { "Cache-Control": "private, no-store" } })

Check which edge actually sets the country: curl -sI https://<host> | grep -i 'cf-ray\|server'. Cloudflare in front → cf-ipcountry (read first). Vercel behind Cloudflare → Vercel's header describes Cloudflare, not the visitor. No geolocation header at all → every visitor counts as "ask"; say so to the user. Make sure no rewrite or middleware swallows /api/region.

5. Gate every tracker

Mount one provider high in the tree and move each tracker behind it. Nothing optional may start at module scope or in server HTML any more.

  • GTM: delete the inline snippet and its <noscript> iframe (a visitor without JavaScript can't consent). useEffect(() => loadGtm(consent, { id }), []). Keep any existing "production only" guard.
  • PostHog: delete the module-scope posthog.init (and instrumentation-client.ts init). useEffect(() => loadPostHog(consent, { client: posthog, token, options: { /* the old init options */ }, onStart }), []) from @turbo-labs/consent/posthog. If the app identifies users, identify in onStart and wherever the user changes, guarded by consent.has("analytics") — an identify before consent is silently dropped. Keep posthog.reset() on logout.
  • Widgets (support chat, feedback, embeds): <WhenConsented category="functional"><Widget /></WhenConsented>. If the widget's provider currently wraps the app, change it to render no children, so consent changes don't remount the tree.
  • Event helpers that push to dataLayer or call an analytics SDK: return early unless consent.has("<category>").
  • Tags inside the GTM container are governed by Consent Mode; tell the user any ad tags there need the matching category.

6. The banner, in the site's own look

<ConsentProvider store={consent} hold={isPopup}>
  {children}
  <ConsentBanner title="Cookies on Acme" intro={<>… <a href="/privacy">privacy policy</a>.</>} />
</ConsentProvider>
  • Built-in styles are :where() rules: plain CSS overrides them, custom properties (--consent-*) restyle them. Tailwind 4 sites: utilities live in a cascade layer and lose to the built-in rules, so pass unstyled, the site's own components={{ Button, Switch }} and classNames per part. Plain-CSS sites: unstyled + className and a small block of rules using the site's tokens.
  • Accept all and Reject all must look the same — map the button's variant ("choice" / "quiet"), never action, to the site's styles.
  • Use semantic colour tokens so dark mode flips with the site.
  • Small windows and modal flows (extension popups, quick-capture windows, an onboarding modal): pass hold while they are on screen — the choice is deferred, not skipped. If those pages are kept deliberately light, load the banner component lazily (next/dynamic, React.lazy) and only render it while useConsent().asking.
  • Add a "Cookie settings" control that calls consent.open(): the footer on a marketing site, the settings page in an app.

7. Scripted browsers

Anything that drives a browser now meets the banner, because its country is unknown: OG-image capture, screenshot scripts, demo recordings, end-to-end tests. Seed a stored choice before the first page loads:

import { consentCookie } from "@turbo-labs/consent"
import { consent } from "../src/lib/consent"   // relative: scripts don't know the alias
await context.addCookies([{ ...consentCookie(consent, "reject-all"), url: BASE_URL }])

Plain .mjs scripts that can't import the TypeScript config can pass { cookie: { name }, version, categories: [{ key, label }] } instead; then add a test that compares those values with the config. Search CI workflows for Playwright/Puppeteer jobs so none is missed.

8. Update the docs

  • Privacy policy: the cookie section should describe what is necessary, each optional category and its tools, who is asked first, and where "Cookie settings" is. List every tool that now loads behind consent among the service providers, with what it receives. Show the user the changed legal text.
  • The project's agent notes (CLAUDE.md, AGENTS.md): where the config lives, that a new tracker must be gated, and how the apps are kept in step.

9. Verify

  • Gates: the project's type-check, lint, unit and end-to-end tests.
  • Unit tests: the config pin (step 3), each event helper dropping events without consent, any hold logic.
  • In a real browser (a production build if the dev server misbehaves), with no stored choice and the country unknown:
    • the banner shows; no request leaves for any third party before a choice (record the hostnames requested);
    • Customize → choose → the cookie holds exactly that choice, the banner stays away after a reload, and only the allowed tools start;
    • "Cookie settings" reopens it; withdrawing a category that ran reloads the page;
    • mobile width, dark mode, and each hold route.
  • Set the region by hand to check both paths: sessionStorage.setItem("<prefix>_region", "DE") (asked) or "US" (not asked), then reload.

Report what was gated, the categories chosen, the region source, anything left ungated and why, and the legal text for the user to review.

相關技能