Cookie consent
A consent banner docked along the bottom of a mock storefront. Accept all and Reject all decide in one click; Customize opens a Modal of categories, each a Switch with a description, with Necessary locked on. Once the reader chooses, the banner collapses into a small “Cookie settings” Button that reopens it, and a toast confirms what was saved.
Source · recipes/cookie-consent.tsx
'use client'
import { BodySmall, Button, Heading, Link, Modal, Stack, Switch, Text, toastSuccess } from '@blocks/design-system'
import { Cookie } from 'lucide-react'
import { useCallback, useId, useRef, useState } from 'react'
import styles from './cookie-consent.module.css'
const categories = [
{
id: 'necessary',
label: 'Necessary',
description: 'Keep you signed in, remember your cart and protect forms from abuse. Always on.',
},
{ id: 'analytics', label: 'Analytics', description: 'Count visits and see which pages help, without identifying you.' },
{ id: 'marketing', label: 'Marketing', description: 'Measure our ads on other sites and show you fewer repeats.' },
{ id: 'preferences', label: 'Preferences', description: 'Remember your language, currency and recently viewed trails.' },
] as const
type Category = (typeof categories)[number]['id']
type Choices = Record<Category, boolean>
const rejectAll: Choices = { necessary: true, analytics: false, marketing: false, preferences: false }
const acceptAll: Choices = { necessary: true, analytics: true, marketing: true, preferences: true }
function summarize(choices: Choices) {
const on = categories.filter((category) => category.id !== 'necessary' && choices[category.id])
return on.length === 0 ? 'Necessary only' : `Necessary, ${on.map((category) => category.label.toLowerCase()).join(', ')}`
}
// A consent banner on a mock storefront. Customize opens a dialog of
// category switches; any choice collapses the banner into a small button
// that reopens it, and focus follows to whichever is on screen.
export default function CookieConsent() {
const titleId = useId()
const [choices, setChoices] = useState<Choices | null>(null)
const [bannerOpen, setBannerOpen] = useState(true)
const [customizing, setCustomizing] = useState(false)
const [draft, setDraft] = useState<Choices>(rejectAll)
const settingsButton = useRef<HTMLButtonElement | null>(null)
const interacted = useRef(false)
// Whichever of the banner and the settings button appears takes focus,
// except on the first render. Stable callbacks run only on mount.
const focusOnMount = useCallback((element: HTMLElement | null) => {
if (element && interacted.current) element.focus()
}, [])
const attachSettingsButton = useCallback(
(button: HTMLButtonElement | null) => {
settingsButton.current = button
focusOnMount(button)
},
[focusOnMount],
)
function decide(next: Choices) {
interacted.current = true
setChoices(next)
setBannerOpen(false)
setCustomizing(false)
toastSuccess('Cookie preferences saved', { description: summarize(next) })
}
function reopen() {
interacted.current = true
setBannerOpen(true)
}
function openCustomize(open: boolean) {
if (open) setDraft(choices ?? rejectAll)
setCustomizing(open)
}
return (
<div className={styles.site}>
{/* A stand-in page so the banner has something to sit on. */}
<div className={styles.page} aria-hidden>
<div className={styles.nav}>
<span />
<span />
<span />
</div>
<div className={styles.hero} />
<div className={styles.lines}>
<span />
<span />
<span />
</div>
</div>
{bannerOpen ? (
<section className={styles.banner} aria-labelledby={titleId}>
<Stack gap="sm">
<Stack direction="row" gap="sm" align="center">
<span className={styles.icon}>
<Cookie aria-hidden size={16} />
</span>
<Heading as="h3" id={titleId} ref={focusOnMount} tabIndex={-1} fontSize="md" margin="none">
We use cookies
</Heading>
</Stack>
<BodySmall color="text-muted" margin="none">
Necessary cookies run Fernway Outfitters. With your OK, others help us measure traffic and ads.{' '}
<Link href="#cookie-policy" fontSize="sm">
Cookie policy
</Link>
</BodySmall>
</Stack>
<div className={styles.actions}>
<Button type="button" variant="link" onClick={() => openCustomize(true)}>
Customize
</Button>
{/* Rejecting is exactly as easy and as prominent as accepting. */}
<Button type="button" variant="primary" onClick={() => decide(rejectAll)}>
Reject all
</Button>
<Button type="button" variant="primary" onClick={() => decide(acceptAll)}>
Accept all
</Button>
</div>
</section>
) : (
<div className={styles.collapsed}>
<Button type="button" size="sm" ref={attachSettingsButton} onClick={reopen}>
<Cookie aria-hidden size={16} />
Cookie settings
</Button>
{choices && (
<Text fontSize="xs" color="text-muted">
{summarize(choices)}
</Text>
)}
</div>
)}
<Modal open={customizing} onOpenChange={openCustomize}>
{/* After a choice the banner is gone, so focus lands on the settings button. */}
<Modal.Content finalFocus={() => settingsButton.current ?? true}>
<Modal.Header>Cookie settings</Modal.Header>
<Modal.Body>Choose which cookies Fernway Outfitters can use. You can change this any time.</Modal.Body>
<ul className={styles.categories}>
{categories.map((category) => (
<li key={category.id}>
<Stack gap="xxs">
<Text id={`${titleId}-${category.id}`} fontWeight="semibold" fontSize="sm">
{category.label}
</Text>
<BodySmall id={`${titleId}-${category.id}-about`} color="text-muted" margin="none">
{category.description}
</BodySmall>
</Stack>
<Switch
aria-labelledby={`${titleId}-${category.id}`}
aria-describedby={`${titleId}-${category.id}-about`}
checked={draft[category.id]}
disabled={category.id === 'necessary'}
onCheckedChange={(checked) => setDraft((current) => ({ ...current, [category.id]: checked }))}
/>
</li>
))}
</ul>
<Modal.Footer>
<Button type="button" variant="ghost" onClick={() => decide(acceptAll)}>
Accept all
</Button>
<Button type="button" variant="primary" onClick={() => decide(draft)}>
Save choices
</Button>
</Modal.Footer>
</Modal.Content>
</Modal>
</div>
)
}How it works
- Rejecting is as easy as accepting. Reject all and Accept all are the same primary
Button, side by side, and Customize is the quietlinkvariant. - Focus follows whatever is on screen. The banner and the settings button take focus as they mount (but not on first render), and the dialog’s
finalFocussends focus to the settings button after a choice, since the button that opened it is gone. - Switches are labelled and described. Each
Switchusesaria-labelledbyfor the category name andaria-describedbyfor what the cookies do. Necessary is disabled and says “Always on” in words. - The page is decoration. The skeleton storefront is drawn with tokens and hidden from assistive technology. A container query lays the answers out side by side on a phone, with Customize beneath them, and the icon sits inline with the title so the banner stays short.
App-owned CSS
The mock storefront, the banner and the collapsed settings button.
/* A mock storefront with the consent banner docked along its bottom edge. */
.site {
container-type: inline-size;
position: relative;
display: flex;
flex-direction: column;
justify-content: flex-end;
min-height: 26rem;
padding: var(--ds-space-lg);
overflow: hidden;
background: var(--ds-color-bg-subtle);
border: var(--ds-border-width-sm) solid var(--ds-color-border-subtle);
border-radius: var(--ds-border-radius-xl);
}
/* Placeholder page content, drawn with tokens and kept out of the a11y tree. */
.page {
position: absolute;
inset: var(--ds-space-lg);
display: grid;
grid-template-rows: auto 8rem auto;
align-content: start;
gap: var(--ds-space-lg);
}
.nav,
.lines {
display: flex;
gap: var(--ds-space-md);
& span {
height: var(--ds-space-md);
background: var(--ds-color-border-subtle);
border-radius: var(--ds-border-radius-pill);
}
}
.nav span {
width: 3rem;
&:first-child {
width: 5rem;
margin-right: auto;
background: var(--ds-color-border);
}
}
.lines {
flex-direction: column;
& span:nth-child(1) {
width: 70%;
}
& span:nth-child(2) {
width: 85%;
}
& span:nth-child(3) {
width: 50%;
}
}
.hero {
background: color-mix(in srgb, var(--ds-color-accent) 12%, transparent);
border-radius: var(--ds-border-radius-md);
}
.banner {
position: relative;
display: grid;
gap: var(--ds-space-md);
padding: var(--ds-space-lg);
background: var(--ds-color-bg);
border: var(--ds-border-width-sm) solid var(--ds-color-border-subtle);
border-radius: var(--ds-border-radius-xl);
box-shadow: var(--ds-shadow-lg);
animation: rise var(--ds-duration-normal) var(--ds-easing-emphasized);
}
.icon {
display: grid;
place-items: center;
flex: none;
width: var(--ds-control-height-sm);
height: var(--ds-control-height-sm);
color: var(--ds-color-accent-text);
background: var(--ds-color-accent-subtle);
border-radius: var(--ds-border-radius-circle);
}
.actions {
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
gap: var(--ds-space-sm);
/* Customize sits apart from the two answers. */
& > :first-child {
margin-right: auto;
}
}
/* On a phone the two answers share a row and Customize goes beneath them. */
@container (max-width: 30rem) {
/* The banner is taller on a phone; two skeleton lines clear its top edge. */
.lines span:nth-child(3) {
display: none;
}
.actions {
display: grid;
grid-template-columns: 1fr 1fr;
}
.actions > :first-child {
grid-column: 1 / -1;
order: 1;
justify-self: center;
margin-right: 0;
}
}
.collapsed {
position: relative;
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--ds-space-md);
align-self: flex-start;
padding: var(--ds-space-xs) var(--ds-space-md) var(--ds-space-xs) var(--ds-space-xs);
background: var(--ds-color-bg);
border: var(--ds-border-width-sm) solid var(--ds-color-border-subtle);
border-radius: var(--ds-border-radius-md);
box-shadow: var(--ds-shadow-md);
animation: rise var(--ds-duration-normal) var(--ds-easing-emphasized);
}
.categories {
display: grid;
margin: 0;
padding: 0 var(--ds-space-lg) var(--ds-space-lg);
list-style: none;
& li {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--ds-space-lg);
padding-block: var(--ds-space-md);
}
& li + li {
border-top: var(--ds-border-width-sm) solid var(--ds-color-border-subtle);
}
}
@keyframes rise {
from {
opacity: 0;
translate: 0 var(--ds-space-md);
}
}
@media (prefers-reduced-motion: reduce) {
.banner,
.collapsed {
animation: none;
}
}