Shilp Sutra
composed · Composed pattern

Consent

@devalok/shilp-sutra/composed/consentView in Storybook
Live preview coming

Hand-curated previews ship in rolling waves. See it live in Storybook →

Reference

Cookie consent: headless engine, GTM/gtag/PostHog loaders, banner + preferences dialog.

The engine is framework-free (createConsentEngine, also at @devalok/shilp-sutra/composed/consent/engine with no React). A port of devalok.in's consent gate: same cookie, same categories, same wording.

Props

options: ConsentEngineOptions (engine config, read once on first render: loaders, categories, version, googleConsentMode, forget, onLoaderError) engine: ConsentEngine (an engine you created with createConsentEngine; takes precedence over options) ui: boolean (default: true; render the built-in banner + preferences dialog. false = build your own on useConsent()) copy: Partial<ConsentCopy> (override any UI string; defaults are devalok.in's wording verbatim) categoryCopy: ConsentCategoryCopyMap (per-row summary + details for essential / analytics / marketing; site-specific, no default) policyHref: string (privacy policy link shown after the banner sentence and the dialog intro) children: ReactNode

ConsentEngineOptions

version: number (default: 1; raise to ask everyone again) cookieName: string (default: "dv_consent") loaders: ConsentLoader[] (vendors gated by consent) categories: ("analytics" | "marketing")[] (default: every category some loader lists; a category not offered gets no row and is never granted, not even by Accept all) googleConsentMode: boolean (default: true; Consent Mode v2 defaults to denied before any loader) forget: Partial<Record<"analytics" | "marketing", RegExp>> (extra cookie / storage-key patterns cleared when that category is denied) onLoaderError: (error: unknown, loader: ConsentLoader) => void (default: console.error)

gtmLoader

containerId: string (REQUIRED, "GTM-…") containerGatesTags: boolean (default: false; true ONLY once every GTM tag has a consent requirement — then GTM loads for either category) origin: string (default: "https://www.googletagmanager.com")

gtagLoader

measurementId: string (REQUIRED, "G-…") config: Record<string, unknown> (extra gtag config params) when: (choice: ConsentChoice) => boolean (default: Analytics granted) origin: string (default: "https://www.googletagmanager.com")

posthogLoader

apiKey: string (REQUIRED, "phc_…") client: () => PostHogLike | Promise<PostHogLike> (REQUIRED; e.g. () => import('posthog-js').then((m) => m.default)) config: Record<string, unknown> (passed to posthog.init; disable_session_recording is forced true) sessionRecording: boolean (default: false; start recording once Analytics is granted) onLoaded: (client: PostHogLike) => void

Defaults

ui=true, version=1, cookieName="dv_consent", googleConsentMode=true

Example

// app/consent.tsx — a client component, rendered once in app/layout.tsx around {children}
'use client'
import {
  ConsentProvider,
  DEVALOK_IN_CATEGORY_COPY,
  gtmLoader,
  posthogLoader,
} from '@devalok/shilp-sutra/composed/consent'

const loaders = [
  gtmLoader({ containerId: 'GTM-XXXXXXX', containerGatesTags: true }),
  posthogLoader({
    apiKey: process.env.NEXT_PUBLIC_POSTHOG_KEY,
    client: () => import('posthog-js').then((m) => m.default),
    config: { api_host: 'https://f.devalok.in', capture_pageview: false },
    sessionRecording: true,
  }),
]

export function Consent({ children }) {
  return (
    <ConsentProvider
      options={{ loaders }}
      categoryCopy={DEVALOK_IN_CATEGORY_COPY}
      policyHref="/privacy#legal-collection"
    >
      {children}
    </ConsentProvider>
  )
}
// A footer "Cookie settings" link — works in a Server Component, no JS of its own:
<a href="/privacy" data-consent-open="">Cookie settings</a>

// Or from client code:
const { open } = useConsentPreferences()
<Button variant="link" onClick={open}>Cookie settings</Button>

// Or from anywhere, outside React:
openConsentPreferences()
// Read the choice (status is "pending" during SSR and the first client render):
const { status, choice } = useConsent()
if (choice.analytics) { /* … */ }

Composability

  • Composes: Banner (the first-visit card), Dialog (preferences), Switch (one per category), Button (Reject all / Accept all are the same soft Button, Reject first), Badge ("Always on"), Link (policy).
  • Context: useConsent() and useConsentPreferences() read the provider. ConsentBanner and ConsentPreferences are exported for custom placement with ui={false}.
  • Part: createConsentEngine is plain TypeScript — no React, no DOM access until start(). Import it from @devalok/shilp-sutra/composed/consent/engine on a site without React.
  • Cookie format is devalok.in's: dv_consent=<version>.a<0|1>.m<0|1>.<unix seconds>, Max-Age 15552000 (180 days), Path=/, SameSite=Lax, Secure on https. Host-only — one choice per site. There is no Domain attribute and no option to add one: a shared cookie would let an Accept on one site turn on tools another site runs and never disclosed, so the consent would not be informed. Same name and format as devalok.in's gate, so the two are interchangeable on one host.
  • Only the categories the site uses. A category no loader collects under (and not declared in categories) has no row and no switch, and is never granted — Accept all included, and a stored grant for it is ignored.
  • Consent Mode v2: defaults are pushed as denied in start(), before any loader. analytics_storage follows Analytics; ad_storage, ad_user_data and ad_personalization follow Marketing. A dv_consent dataLayer event carries dv_analytics / dv_marketing after each update (same as devalok.in, for GTM triggers).
  • Loaders never run before consent. Each runs at most once per page, when its when() holds (default: all its categories granted). Custom loaders: { id, categories, when?, load(ctx), withdraw?(ctx), forget? }; ctx gives injectScript(src) and gtag(...).
  • Withdrawal reloads. Taking back a category a loaded vendor uses first calls the loader's withdraw() (PostHog: stop recording, opt out), THEN deletes that category's cookies (on the host and every parent domain) and its localStorage / sessionStorage keys, then reloads — a loaded script cannot be unloaded. Clearing comes last because an opt-out writes keys of its own.
  • Load-time sweep. Every page load clears the declared keys of each category that is denied or not yet chosen, so leftovers from a withdrawal or an older version do not persist. Declare a custom vendor's keys in its loader's forget (or options.forget) and they are swept the same way.
  • Small screens: the banner is a fixed card across the bottom; an in-flow spacer of its height is rendered at the end of the provider's children so the page end can always scroll clear of it. It never takes focus and is not modal.
  • Accessibility: banner is a labelled region; dialog traps focus, closes on Escape without saving and returns focus; each Switch is labelled by its category and described by its summary; saved choices are announced in a polite live region.

Gotchas

  • Render ConsentProvider ONCE, high in the root layout, wrapping the page content (the banner spacer goes after the children). options are read on the first render only.
  • status is "pending" on the server and the first client render — never gate content visibility on consent during SSR, or hydration mismatches.
  • categoryCopy has no default: what each category's vendors do is site-specific. DEVALOK_IN_CATEGORY_COPY names devalok.in's vendors (Cloudflare, GA4, Factors.ai) — use it only on a site that runs exactly those. POSTHOG_CATEGORY_COPY_PLACEHOLDER is a marked placeholder, not publishable copy.
  • gtmLoader defaults to loading only when BOTH categories are granted, because Custom HTML tags ignore Consent Mode. Set containerGatesTags: true only after every tag in the container has a consent requirement and Tag Assistant shows them blocked.
  • Do NOT also call posthog.init yourself or add a GTM snippet to the page head — that loads the vendor before consent. Let the loaders do it.
  • A site with no marketing vendor shows no Marketing row. A vendor that does not run through a loader must have its category declared in categories, or that category is never offered and never granted.
  • posthog-js is NOT a dependency of Shilp Sutra; the site installs it and passes client.

Changes

v0.61.1

  • Fixed PostHog's ph_*_posthog cookie and __ph_opt_in_out_* / session_registered_properties storage keys survived a withdrawal: withdraw() now runs before the clear, every load sweeps denied categories, and posthogLoader declares all of PostHog's keys.

v0.61.0

  • Added Initial release: createConsentEngine, gtmLoader, gtagLoader, posthogLoader, ConsentProvider, ConsentBanner, ConsentPreferences, useConsent, useConsentPreferences, openConsentPreferences