Cookie consent
Ask once, with a switch per category.
Installation
Run the CLI
Run
pnpm dlx asta-ui@latest initonce, then this. The file lands incomponents/astabyte/, installsradix-ui@base-ui/reactand the colour tokens go into your CSS. This is the Radix build. Drop --radix for Base UI.This is the Base UI build, the default. Want Radix? Add --radix.$ pnpm dlx asta-ui@latest add cookie-consent --radixOr install the package
Don’t want the file? Import from
asta-uiasta-ui/baseand update withpnpm update asta-ui. Add the stylesheet once. More.$ pnpm add asta-ui radix-ui @base-ui/reactimport { CookieConsent } from "asta-ui";import { CookieConsent } from "asta-ui/base";Or copy it by hand
Install
radix-ui@base-ui/react, then copy these files. Keep the paths, or fix the@/imports. Then add the tokens fromglobals.css."use client"; import { useEffect, useId, useRef, useState, type ReactNode } from "react"; import { Button } from "@/components/kit/button"; import { Switch } from "@/components/kit/switch"; const cx = (...c: (string | false | null | undefined)[]) => c.filter(Boolean).join(" "); const KEYFRAMES = `@keyframes asta-consent-in { from { opacity: 0; transform: translateY(18px) scale(.98) } } @keyframes asta-consent-out { to { opacity: 0; transform: translateY(18px) scale(.98) } } @keyframes asta-consent-view { from { opacity: 0; transform: translateX(var(--asta-consent-dx, 12px)) } } @media (prefers-reduced-motion: reduce) { .asta-consent, .asta-consent-view { animation-duration: 1ms !important } }`; export interface ConsentCategory { id: string; label: string; description: string; /** Always on and can't be switched off, e.g. cookies the site needs to work. */ required?: boolean; /** Starting value in the preferences view. */ defaultOn?: boolean; } export type Consent = Record<string, boolean>; export const DEFAULT_CONSENT_CATEGORIES: ConsentCategory[] = [ { id: "necessary", label: "Strictly necessary", description: "Sign-in, security and your cart. The site can't work without these.", required: true }, { id: "preferences", label: "Preferences", description: "Remember your language, region and display settings.", defaultOn: true }, { id: "analytics", label: "Analytics", description: "Count visits and see which pages help, with no personal profile." }, { id: "marketing", label: "Marketing", description: "Measure campaigns and show more relevant ads elsewhere." }, ]; export interface CookieConsentProps { categories?: ConsentCategory[]; title?: string; message?: ReactNode; /** Link to the cookie policy. */ policyHref?: string; /** Saves the choice in localStorage under this key, and stays hidden once a choice is saved. */ storageKey?: string; onConsent?: (consent: Consent) => void; /** Where it sits. Default bottom-left. */ position?: "bottom-left" | "bottom-right" | "bottom"; /** Position inside the nearest positioned parent instead of the viewport (previews, docs). */ contained?: boolean; /** Controlled visibility. Leave it out and the banner manages itself. */ open?: boolean; onOpenChange?: (open: boolean) => void; className?: string; } const POS = { "bottom-left": "left-4 bottom-4", "bottom-right": "right-4 bottom-4", bottom: "inset-x-4 bottom-4 mx-auto" }; /** * A cookie banner that asks once. It slides up from the bottom with Accept all, Reject all and Customize. * Customize slides over to a switch per category, with the required ones locked on. Any choice slides it away * and hands you the result, and `storageKey` remembers it. */ export function CookieConsent({ categories = DEFAULT_CONSENT_CATEGORIES, title = "We use cookies", message = "Some keep the site working. Others help us understand what's useful. You choose which.", policyHref, storageKey, onConsent, position = "bottom-left", contained, open, onOpenChange, className, }: CookieConsentProps) { const id = useId(); const [self, setSelf] = useState(false); const [leaving, setLeaving] = useState(false); const [view, setView] = useState<"summary" | "custom">("summary"); const [prefs, setPrefs] = useState<Consent>(() => Object.fromEntries(categories.map((c) => [c.id, !!(c.required || c.defaultOn)]))); const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined); const shown = (open ?? self) || leaving; // Decide on mount: hidden if a choice is already stored. useEffect(() => { if (open !== undefined) return; let stored: string | null = null; try { stored = storageKey ? localStorage.getItem(storageKey) : null; } catch {} const t = setTimeout(() => setSelf(!stored), 400); return () => clearTimeout(t); }, [storageKey, open]); useEffect(() => () => clearTimeout(timer.current), []); // Reopening starts on the summary again. useEffect(() => { if (open) { const t = setTimeout(() => setView("summary"), 0); return () => clearTimeout(t); } }, [open]); const decide = (consent: Consent) => { try { if (storageKey) localStorage.setItem(storageKey, JSON.stringify({ consent, at: new Date().toISOString() })); } catch {} onConsent?.(consent); setLeaving(true); timer.current = setTimeout(() => { setLeaving(false); setSelf(false); setView("summary"); }, 280); onOpenChange?.(false); }; const all = (on: boolean) => Object.fromEntries(categories.map((c) => [c.id, c.required ? true : on])); if (!shown) return null; return ( <section role="dialog" aria-modal="false" aria-labelledby={`${id}-t`} aria-describedby={`${id}-d`} className={cx( "asta-consent z-50 w-[calc(100%-2rem)] max-w-[400px] rounded-[14px] bg-paper p-5 text-ink", "shadow-[0_0_0_1px_color-mix(in_srgb,var(--color-ink)_9%,transparent),0_24px_48px_-20px_rgb(0_0_0/0.35),0_2px_8px_-2px_rgb(0_0_0/0.08)]", contained ? "absolute" : "fixed", POS[position], leaving ? "pointer-events-none animate-[asta-consent-out_.28s_cubic-bezier(.16,1,.3,1)_both]" : "animate-[asta-consent-in_.5s_cubic-bezier(.16,1,.3,1)_both]", className, )} > <style href="asta-cookie-consent" precedence="asta">{KEYFRAMES}</style> {view === "summary" ? ( <div key="summary" className="asta-consent-view animate-[asta-consent-view_.35s_cubic-bezier(.16,1,.3,1)_both] [--asta-consent-dx:-12px]"> <h2 id={`${id}-t`} className="text-[15px] font-medium tracking-[-0.01em]"> {title} </h2> <p id={`${id}-d`} className="mt-1.5 text-[13px] leading-relaxed text-mute"> {message}{" "} {policyHref && ( <a href={policyHref} className="text-ink underline decoration-[color-mix(in_srgb,var(--color-ink)_30%,transparent)] underline-offset-2 hover:decoration-current"> Cookie policy </a> )} </p> <div className="mt-4 flex flex-wrap items-center gap-2"> <Button size="sm" onClick={() => decide(all(true))}> Accept all </Button> <Button size="sm" variant="outline" onClick={() => decide(all(false))}> Reject all </Button> <Button size="sm" variant="ghost" className="ml-auto" onClick={() => setView("custom")}> Customize </Button> </div> </div> ) : ( <div key="custom" className="asta-consent-view animate-[asta-consent-view_.35s_cubic-bezier(.16,1,.3,1)_both]"> <div className="flex items-center gap-2"> <button type="button" onClick={() => setView("summary")} aria-label="Back" className="-ml-1.5 flex h-7 w-7 items-center justify-center rounded-md text-mute outline-none transition-colors hover:bg-paper-2 hover:text-ink focus-visible:ring-2 focus-visible:ring-brand/50" > <svg viewBox="0 0 24 24" className="h-4 w-4" fill="none" stroke="currentColor" strokeWidth="2.55" strokeLinecap="round" strokeLinejoin="round" aria-hidden> <path d="m14.5 6-6 6 6 6" /> </svg> </button> <h2 id={`${id}-t`} className="text-[15px] font-medium tracking-[-0.01em]"> Cookie preferences </h2> </div> <p id={`${id}-d`} className="sr-only"> Choose which kinds of cookies to allow. </p> <ul className="mt-3 flex flex-col gap-1"> {categories.map((c) => ( <li key={c.id} className="flex items-start gap-4 rounded-[10px] bg-paper-2 px-3.5 py-3"> <div className="min-w-0 flex-1"> <p className="flex items-center gap-2 text-[13px] font-medium"> {c.label} {c.required && <span className="rounded-[4px] bg-paper px-1.5 text-[10.5px] font-normal leading-[18px] text-mute">Always on</span>} </p> <p className="mt-0.5 text-[12px] leading-snug text-mute">{c.description}</p> </div> <Switch size="sm" checked={prefs[c.id]} disabled={c.required} onCheckedChange={(v) => setPrefs((p) => ({ ...p, [c.id]: v }))} aria-label={c.label} /> </li> ))} </ul> <div className="mt-4 flex items-center justify-end gap-2"> <Button size="sm" variant="outline" onClick={() => decide(all(false))}> Reject all </Button> <Button size="sm" onClick={() => decide(prefs)}> Save choices </Button> </div> </div> )} </section> ); } export default CookieConsent;"use client"; import { useEffect, useId, useRef, useState, type ReactNode } from "react"; import { Button } from "@/components/kit/base/button"; import { Switch } from "@/components/kit/base/switch"; const cx = (...c: (string | false | null | undefined)[]) => c.filter(Boolean).join(" "); const KEYFRAMES = `@keyframes asta-consent-in { from { opacity: 0; transform: translateY(18px) scale(.98) } } @keyframes asta-consent-out { to { opacity: 0; transform: translateY(18px) scale(.98) } } @keyframes asta-consent-view { from { opacity: 0; transform: translateX(var(--asta-consent-dx, 12px)) } } @media (prefers-reduced-motion: reduce) { .asta-consent, .asta-consent-view { animation-duration: 1ms !important } }`; export interface ConsentCategory { id: string; label: string; description: string; /** Always on and can't be switched off, e.g. cookies the site needs to work. */ required?: boolean; /** Starting value in the preferences view. */ defaultOn?: boolean; } export type Consent = Record<string, boolean>; export const DEFAULT_CONSENT_CATEGORIES: ConsentCategory[] = [ { id: "necessary", label: "Strictly necessary", description: "Sign-in, security and your cart. The site can't work without these.", required: true }, { id: "preferences", label: "Preferences", description: "Remember your language, region and display settings.", defaultOn: true }, { id: "analytics", label: "Analytics", description: "Count visits and see which pages help, with no personal profile." }, { id: "marketing", label: "Marketing", description: "Measure campaigns and show more relevant ads elsewhere." }, ]; export interface CookieConsentProps { categories?: ConsentCategory[]; title?: string; message?: ReactNode; /** Link to the cookie policy. */ policyHref?: string; /** Saves the choice in localStorage under this key, and stays hidden once a choice is saved. */ storageKey?: string; onConsent?: (consent: Consent) => void; /** Where it sits. Default bottom-left. */ position?: "bottom-left" | "bottom-right" | "bottom"; /** Position inside the nearest positioned parent instead of the viewport (previews, docs). */ contained?: boolean; /** Controlled visibility. Leave it out and the banner manages itself. */ open?: boolean; onOpenChange?: (open: boolean) => void; className?: string; } const POS = { "bottom-left": "left-4 bottom-4", "bottom-right": "right-4 bottom-4", bottom: "inset-x-4 bottom-4 mx-auto" }; /** * A cookie banner that asks once. It slides up from the bottom with Accept all, Reject all and Customize. * Customize slides over to a switch per category, with the required ones locked on. Any choice slides it away * and hands you the result, and `storageKey` remembers it. */ export function CookieConsent({ categories = DEFAULT_CONSENT_CATEGORIES, title = "We use cookies", message = "Some keep the site working. Others help us understand what's useful. You choose which.", policyHref, storageKey, onConsent, position = "bottom-left", contained, open, onOpenChange, className, }: CookieConsentProps) { const id = useId(); const [self, setSelf] = useState(false); const [leaving, setLeaving] = useState(false); const [view, setView] = useState<"summary" | "custom">("summary"); const [prefs, setPrefs] = useState<Consent>(() => Object.fromEntries(categories.map((c) => [c.id, !!(c.required || c.defaultOn)]))); const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined); const shown = (open ?? self) || leaving; // Decide on mount: hidden if a choice is already stored. useEffect(() => { if (open !== undefined) return; let stored: string | null = null; try { stored = storageKey ? localStorage.getItem(storageKey) : null; } catch {} const t = setTimeout(() => setSelf(!stored), 400); return () => clearTimeout(t); }, [storageKey, open]); useEffect(() => () => clearTimeout(timer.current), []); // Reopening starts on the summary again. useEffect(() => { if (open) { const t = setTimeout(() => setView("summary"), 0); return () => clearTimeout(t); } }, [open]); const decide = (consent: Consent) => { try { if (storageKey) localStorage.setItem(storageKey, JSON.stringify({ consent, at: new Date().toISOString() })); } catch {} onConsent?.(consent); setLeaving(true); timer.current = setTimeout(() => { setLeaving(false); setSelf(false); setView("summary"); }, 280); onOpenChange?.(false); }; const all = (on: boolean) => Object.fromEntries(categories.map((c) => [c.id, c.required ? true : on])); if (!shown) return null; return ( <section role="dialog" aria-modal="false" aria-labelledby={`${id}-t`} aria-describedby={`${id}-d`} className={cx( "asta-consent z-50 w-[calc(100%-2rem)] max-w-[400px] rounded-[14px] bg-paper p-5 text-ink", "shadow-[0_0_0_1px_color-mix(in_srgb,var(--color-ink)_9%,transparent),0_24px_48px_-20px_rgb(0_0_0/0.35),0_2px_8px_-2px_rgb(0_0_0/0.08)]", contained ? "absolute" : "fixed", POS[position], leaving ? "pointer-events-none animate-[asta-consent-out_.28s_cubic-bezier(.16,1,.3,1)_both]" : "animate-[asta-consent-in_.5s_cubic-bezier(.16,1,.3,1)_both]", className, )} > <style href="asta-cookie-consent" precedence="asta">{KEYFRAMES}</style> {view === "summary" ? ( <div key="summary" className="asta-consent-view animate-[asta-consent-view_.35s_cubic-bezier(.16,1,.3,1)_both] [--asta-consent-dx:-12px]"> <h2 id={`${id}-t`} className="text-[15px] font-medium tracking-[-0.01em]"> {title} </h2> <p id={`${id}-d`} className="mt-1.5 text-[13px] leading-relaxed text-mute"> {message}{" "} {policyHref && ( <a href={policyHref} className="text-ink underline decoration-[color-mix(in_srgb,var(--color-ink)_30%,transparent)] underline-offset-2 hover:decoration-current"> Cookie policy </a> )} </p> <div className="mt-4 flex flex-wrap items-center gap-2"> <Button size="sm" onClick={() => decide(all(true))}> Accept all </Button> <Button size="sm" variant="outline" onClick={() => decide(all(false))}> Reject all </Button> <Button size="sm" variant="ghost" className="ml-auto" onClick={() => setView("custom")}> Customize </Button> </div> </div> ) : ( <div key="custom" className="asta-consent-view animate-[asta-consent-view_.35s_cubic-bezier(.16,1,.3,1)_both]"> <div className="flex items-center gap-2"> <button type="button" onClick={() => setView("summary")} aria-label="Back" className="-ml-1.5 flex h-7 w-7 items-center justify-center rounded-md text-mute outline-none transition-colors hover:bg-paper-2 hover:text-ink focus-visible:ring-2 focus-visible:ring-brand/50" > <svg viewBox="0 0 24 24" className="h-4 w-4" fill="none" stroke="currentColor" strokeWidth="2.55" strokeLinecap="round" strokeLinejoin="round" aria-hidden> <path d="m14.5 6-6 6 6 6" /> </svg> </button> <h2 id={`${id}-t`} className="text-[15px] font-medium tracking-[-0.01em]"> Cookie preferences </h2> </div> <p id={`${id}-d`} className="sr-only"> Choose which kinds of cookies to allow. </p> <ul className="mt-3 flex flex-col gap-1"> {categories.map((c) => ( <li key={c.id} className="flex items-start gap-4 rounded-[10px] bg-paper-2 px-3.5 py-3"> <div className="min-w-0 flex-1"> <p className="flex items-center gap-2 text-[13px] font-medium"> {c.label} {c.required && <span className="rounded-[4px] bg-paper px-1.5 text-[10.5px] font-normal leading-[18px] text-mute">Always on</span>} </p> <p className="mt-0.5 text-[12px] leading-snug text-mute">{c.description}</p> </div> <Switch size="sm" checked={prefs[c.id]} disabled={c.required} onCheckedChange={(v) => setPrefs((p) => ({ ...p, [c.id]: v }))} aria-label={c.label} /> </li> ))} </ul> <div className="mt-4 flex items-center justify-end gap-2"> <Button size="sm" variant="outline" onClick={() => decide(all(false))}> Reject all </Button> <Button size="sm" onClick={() => decide(prefs)}> Save choices </Button> </div> </div> )} </section> ); } export default CookieConsent;Or ask your AI agent
Paste this into Claude Code, Cursor, Codex, v0 or Lovable. Fill in the last line. More in Prompts.
Add the Astabyte UI Cookie consent component to my project. Ask once, with a switch per category. It includes: accept/reject, categories, required, storageKey, contained, positions. Install it (Radix build): ```sh pnpm dlx asta-ui@latest add cookie-consent --radix ``` Or with the shadcn CLI: ```sh pnpm dlx shadcn@latest add https://ui.astabyte.com/r/cookie-consent.json ``` If the project isn't set up yet, run `pnpm dlx asta-ui@latest init --radix` first: it runs `shadcn init` when needed and adds the @astabyte registry (Next.js, Vite, React Router, Astro, TanStack Start; Tailwind CSS v4). Import it like this: ```tsx import { Button } from "@/components/astabyte/button"; import { CookieConsent, type Consent } from "@/components/astabyte/cookie-consent"; ``` Usage example and props: https://ui.astabyte.com/cookie-consent Full catalogue for context: https://ui.astabyte.com/llms.txt Rules: - Keep the colour tokens (paper, paper-2, ink, ink-2, mute, brand). Don't restyle with hard-coded colours; rebrand by changing the token values in the CSS. - Keep the motion as it is: transform and opacity only, and the prefers-reduced-motion fallback. - Keep keyboard, focus and ARIA behaviour (interactive pieces are built on Radix primitives from the radix-ui package). - Stay on Radix: install other Astabyte UI components with `--radix` so the project uses one primitive library. - Use fake data and fake brand names in examples. Use it to: [describe where it goes and what it should do]Add the Astabyte UI Cookie consent component to my project. Ask once, with a switch per category. It includes: accept/reject, categories, required, storageKey, contained, positions. Install it (Base UI build): ```sh pnpm dlx asta-ui@latest add cookie-consent ``` Or with the shadcn CLI: ```sh pnpm dlx shadcn@latest add https://ui.astabyte.com/r/base/cookie-consent.json ``` If the project isn't set up yet, run `pnpm dlx asta-ui@latest init` first: it runs `shadcn init` when needed and adds the @astabyte registry (Next.js, Vite, React Router, Astro, TanStack Start; Tailwind CSS v4). Import it like this: ```tsx import { Button } from "@/components/astabyte/button"; import { CookieConsent, type Consent } from "@/components/astabyte/cookie-consent"; ``` Usage example and props: https://ui.astabyte.com/cookie-consent Full catalogue for context: https://ui.astabyte.com/llms.txt Rules: - Keep the colour tokens (paper, paper-2, ink, ink-2, mute, brand). Don't restyle with hard-coded colours; rebrand by changing the token values in the CSS. - Keep the motion as it is: transform and opacity only, and the prefers-reduced-motion fallback. - Keep keyboard, focus and ARIA behaviour (interactive pieces are built on Base UI primitives from the @base-ui/react package). - Stay on Base UI: install other Astabyte UI components without `--radix` so the project uses one primitive library. - Use fake data and fake brand names in examples. Use it to: [describe where it goes and what it should do]Or use plain HTML + CSS
Not on React? Use it from Django, Rails, Laravel, Go
html/template, htmx or a static page. Loadasta.cssandasta.jsonce (thehead.htmltab), then paste the markup. Theui.astabyte.com/cdnlink is temporary: pin a version from jsDelivr for production. More in HTML + CSS.<!-- asta.js remembers the choice in localStorage under the data-asta-consent key and fires "asta:consent". Clear it to see the banner again. --> <div style="position:relative;min-height:340px;border-radius:12px;background:var(--paper-2);overflow:hidden"> <div class="asta-consent asta-consent-contained" data-asta-consent="asta-example-consent" data-view="summary" role="dialog" aria-label="Cookie settings"> <div class="asta-consent-summary"> <p class="asta-consent-title">We use a few cookies</p> <p class="asta-consent-text">Necessary ones keep astabyte.com working. With your OK we also measure visits and remember your settings. <a href="#">Cookie policy</a></p> <div class="asta-consent-actions"><button type="button" class="asta-btn asta-btn-ghost asta-btn-sm" data-asta-consent-customize><span class="asta-btn-label">Customize</span></button><button type="button" class="asta-btn asta-btn-outline asta-btn-sm" data-asta-consent-reject><span class="asta-btn-label">Reject</span></button><button type="button" class="asta-btn asta-btn-accent asta-btn-sm" data-asta-consent-accept><span class="asta-btn-label">Accept all</span></button></div> </div> <form class="asta-consent-custom"> <p class="asta-consent-title">Cookie settings</p> <div class="asta-consent-row"><span class="asta-consent-row-text">Necessary<span>Sign-in and security. Always on.</span></span><label class="asta-switch asta-switch-sm"><span class="asta-switch-track"><input type="checkbox" role="switch" class="asta-switch-input" name="necessary" aria-label="Necessary" checked disabled><span class="asta-switch-thumb" aria-hidden="true"></span></span></label></div> <div class="asta-consent-row"><span class="asta-consent-row-text">Analytics<span>Anonymous visit counts.</span></span><label class="asta-switch asta-switch-sm"><span class="asta-switch-track"><input type="checkbox" role="switch" class="asta-switch-input" name="analytics" aria-label="Analytics"><span class="asta-switch-thumb" aria-hidden="true"></span></span></label></div> <div class="asta-consent-row"><span class="asta-consent-row-text">Preferences<span>Theme and language.</span></span><label class="asta-switch asta-switch-sm"><span class="asta-switch-track"><input type="checkbox" role="switch" class="asta-switch-input" name="preferences" aria-label="Preferences" checked><span class="asta-switch-thumb" aria-hidden="true"></span></span></label></div> <div class="asta-consent-actions"><button type="button" class="asta-btn asta-btn-ghost asta-btn-sm" data-asta-consent-back><span class="asta-btn-label">Back</span></button><button type="button" class="asta-btn asta-btn-accent asta-btn-sm" data-asta-consent-save><span class="asta-btn-label">Save choices</span></button></div> </form> </div> </div>
Usage
The demo above, as code.
"use client";
import { useState } from "react";
import { Button } from "@/components/astabyte/button";
import { CookieConsent, type Consent } from "@/components/astabyte/cookie-consent";
export default function CookieConsentDemo() {
const [round, setRound] = useState(0);
const [result, setResult] = useState<Consent | null>(null);
const on = result ? Object.entries(result).filter(([, v]) => v).map(([k]) => k) : [];
return (
<div className="relative flex min-h-[520px] w-full overflow-hidden p-6 sm:p-10">
{/* A page behind the banner */}
<div className="mx-auto flex w-full max-w-[620px] flex-col gap-3 pt-2 sm:items-end sm:text-right">
<p className="font-mono text-[11px] uppercase tracking-wider text-mute">astabyte.com</p>
<p className="text-[26px] font-medium leading-[1.1] tracking-[-0.035em] text-ink sm:text-[32px]">Studio tools for small teams</p>
<p className="max-w-[420px] text-[13.5px] leading-relaxed text-mute">Plan, design and ship from one place. Your choice below is only kept in this preview.</p>
<div className="mt-2 flex flex-col gap-2 rounded-xl bg-paper-2 px-4 py-3 text-left text-[12.5px] sm:w-[280px]">
<p className="font-medium text-ink">Saved choice</p>
<p className="text-mute">{result ? (on.length ? on.join(", ") : "none") : "Waiting for a choice…"}</p>
<Button
size="xs"
variant="outline"
className="self-start"
disabled={!result}
onClick={() => {
setResult(null);
setRound((r) => r + 1);
}}
>
Show the banner again
</Button>
</div>
</div>
<CookieConsent key={round} contained policyHref="#cookie-consent" onConsent={setResult} />
</div>
);
}