Cookie Consent
Choose required-only, all optional, or custom cookie preferences, save locally, and reopen the panel.
pnpm dlx shadcn@latest add @haze/cookie-consent---
import { ChevronDown } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";
import Button from "./button.astro";
import Checkbox from "./checkbox.astro";
interface Props {
id: string;
storageKey?: string;
text?: string;
privacyHref?: string;
class?: string;
}
const { id, storageKey = "haze-consent", text = "Choose which optional cookies you allow. Required cookies keep your session working.", privacyHref = "/privacy", class: className } = Astro.props;
---
<section data-haze-cookie-consent data-storage-key={storageKey} aria-label="Cookie preferences" class={cn("group/consent min-w-0", className)}>
<form class="grid min-w-0 gap-3 rounded-xl border border-border bg-popover p-4.5 shadow-float transition-[opacity,translate] duration-200 ease-snappy motion-reduce:transition-none [&[hidden]]:hidden">
<p class="text-[1.0625rem] leading-[1.4] font-medium tracking-[-0.01em]">Your cookie choices</p>
<p class="text-[0.8125rem] leading-[1.4] text-muted-foreground">{text} <a href={privacyHref} class="rounded-sm text-foreground underline underline-offset-4 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring">Privacy policy</a></p>
<details class="group/prefs min-w-0 rounded-lg border border-border bg-card p-3">
<summary class="flex min-h-6 cursor-pointer list-none items-center justify-between gap-2 rounded-sm text-[0.8125rem]/5 font-medium focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring [&::-webkit-details-marker]:hidden">Manage preferences<ChevronDown aria-hidden="true" class="size-3.5 shrink-0 transition-[rotate] duration-200 ease-snappy group-open/prefs:rotate-180" /></summary>
<div class="mt-3 grid gap-3">
<Checkbox id={`${id}-required`} name="required" label="Required cookies" checked disabled />
<Checkbox id={`${id}-analytics`} name="analytics" label="Usage analytics" />
<Checkbox id={`${id}-marketing`} name="marketing" label="Marketing cookies" />
<Button type="submit" name="choice" value="custom" variant="secondary" size="sm">Save preferences</Button>
</div>
</details>
<div class="flex flex-wrap gap-2">
<Button type="submit" name="choice" value="all" size="sm">Accept optional cookies</Button>
<Button type="submit" name="choice" value="required" size="sm" variant="outline">Required only</Button>
</div>
</form>
<Button data-cookie-reopen hidden variant="outline" size="sm" class="[&[hidden]]:hidden">Cookie preferences</Button>
<p data-cookie-status role="status" class="sr-only"></p>
</section>
<script>
function enhance(root: HTMLElement) {
if (root.hasAttribute("data-enhanced")) return;
const form = root.querySelector("form");
const reopen = root.querySelector<HTMLButtonElement>("[data-cookie-reopen]");
const status = root.querySelector<HTMLElement>("[data-cookie-status]");
if (!form || !reopen || !status) return;
const fields = { analytics: form.querySelector<HTMLInputElement>("[name=analytics]")!, marketing: form.querySelector<HTMLInputElement>("[name=marketing]")! };
const key = root.dataset.storageKey!;
const showSaved = () => { form.hidden = true; reopen.hidden = false; };
try {
const stored = JSON.parse(localStorage.getItem(key) ?? "null");
if (stored?.version === 1 && typeof stored.analytics === "boolean" && typeof stored.marketing === "boolean") {
fields.analytics.checked = stored.analytics;
fields.marketing.checked = stored.marketing;
showSaved();
}
} catch { /* The preference controls remain available when storage is unavailable. */ }
let leaving = false;
// Fades the form out, then hands over to the reopen button; instant under reduced motion.
const leave = (done: () => void) => {
if (matchMedia("(prefers-reduced-motion: reduce)").matches) { done(); return; }
leaving = true;
const finish = () => {
if (!leaving) return;
leaving = false;
form.removeEventListener("transitionend", onEnd);
clearTimeout(timer);
done();
form.classList.remove("opacity-0", "-translate-y-1");
};
const onEnd = (event: TransitionEvent) => { if (event.target === form && event.propertyName === "opacity") finish(); };
const timer = window.setTimeout(finish, 260);
form.addEventListener("transitionend", onEnd);
form.classList.add("opacity-0", "-translate-y-1");
};
form.addEventListener("submit", event => {
event.preventDefault();
if (leaving) return;
const choice = (event.submitter as HTMLButtonElement | null)?.value ?? "custom";
const preferences = { version: 1, required: true, analytics: choice === "all" || (choice === "custom" && fields.analytics.checked), marketing: choice === "all" || (choice === "custom" && fields.marketing.checked) };
fields.analytics.checked = preferences.analytics;
fields.marketing.checked = preferences.marketing;
try { localStorage.setItem(key, JSON.stringify(preferences)); } catch { /* Current page still applies the selected preference. */ }
leave(() => { showSaved(); reopen.classList.add("motion-safe:animate-rise"); reopen.focus(); });
status.textContent = "Cookie preferences saved.";
root.dispatchEvent(new CustomEvent("haze:consent-change", { bubbles: true, detail: preferences }));
});
reopen.addEventListener("click", () => { reopen.classList.remove("motion-safe:animate-rise"); reopen.hidden = true; form.hidden = false; form.querySelector<HTMLElement>("summary")?.focus(); });
root.setAttribute("data-enhanced", "");
}
const init = () => document.querySelectorAll<HTMLElement>("[data-haze-cookie-consent]").forEach(enhance);
init();
if (!document.documentElement.hasAttribute("data-haze-cookie-consent-listener")) {
document.documentElement.setAttribute("data-haze-cookie-consent-listener", "");
document.addEventListener("astro:page-load", init);
}
</script>When to use
- A site needs explicit settings for analytics and marketing storage.
- Visitors should be able to revisit their previous choices.
When not to use
- The application needs a remote consent history. Add server persistence to the consent-change event.
Installation
Add the Haze registry to components.json once, then install Cookie Consent with the shadcn CLI. Works in any Astro project with Tailwind CSS v4.
pnpm dlx shadcn@latest add @haze/cookie-consentnpx shadcn@latest add @haze/cookie-consentyarn dlx shadcn@latest add @haze/cookie-consentbunx --bun shadcn@latest add @haze/cookie-consentFirst time? Registry and theme setup
1. Add to components.json:
{
"registries": {
"@haze": "http://localhost:4329/r/{name}.json"
}
}2. Install the theme once: npx shadcn@latest add @haze/theme, then import it after Tailwind in your global CSS:@import "./haze.css";
API reference
| Prop | Type | Default | Description |
|---|---|---|---|
| id* | string | – | Prefix for category input IDs. |
| storageKey | string | – | Versioned local storage key. Defaults to haze-consent. |
| text | string | – | Explanation of the available storage categories. |
| privacyHref | string | – | Link to the site's privacy policy. |
| class | string | – | Additional classes on the component wrapper. |
Keyboard interactions
- Space
- Toggle an optional category or open preference details.
- Enter
- Save the choice using a focused button.
Accessibility
- Analytics and marketing begin unchecked. Required cookies are labelled and locked. Saved preferences are versioned and validated before reuse.
- The host receives haze:consent-change and controls any associated services. Reopening and saving keep keyboard focus on the visible controls.
Notes for AI
Copy into Claude Code, Cursor, Codex or any coding agent. Agents can also read the Markdown version of this page.
Install and use
Install the Haze UI component "Cookie Consent" with `npx shadcn@latest add @haze/cookie-consent`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "http://localhost:4329/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import CookieConsent from "@/components/haze/ui/cookie-consent.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: http://localhost:4329/ui/cookie-consent.md
Customize with real content
Adapt the Haze cookie-consent ui for our product. Replace the demo values of these props with our real content: id, storageKey, text, privacyHref, class. Keep the layout, the heading level rules and these accessibility details: Analytics and marketing begin unchecked. Required cookies are labelled and locked. Saved preferences are versioned and validated before reuse. The host receives haze:consent-change and controls any associated services. Reopening and saving keep keyboard focus on the visible controls. Do not add raw color classes; use the Haze tokens.
Choose the right block
Before using cookie-consent, check it fits: use it when a site needs explicit settings for analytics and marketing storage.; visitors should be able to revisit their previous choices.. Avoid it when the application needs a remote consent history. add server persistence to the consent-change event.. Alternatives: @haze/dialog, @haze/checkbox-group.
Dependencies
- npm: @lucide/astro
- @haze/button
- @haze/checkbox
- @haze/utils
- @haze/theme (one-time setup)
Source · Original Haze UI work.