UI

Cookies

A non-modal consent bar that morphs into a preferences panel and folds into a reopen button.

import { CookieConsent } from '@uthereal/ui/cookie-consent'

Cookie consent playground

Loading interactive preview…

Overview

CookieConsent renders a single non-modal floating surface anchored to the bottom edge. It transitions between three faces: a consent bar (up to 660 px wide), a category preferences panel (up to 420 px wide), and a 44 px circular reopen button once a visitor saves a choice.

Reject all and Accept all carry equal visual weight in both the bar and the panel. Required categories display "Always on" instead of a toggle, and optional categories start off before a choice is saved. Storage reads wait until client hydration so server markup matches and returning visitors never see a flash of the bar.

Use CookieConsent for non-blocking privacy consent that stays reachable after dismissal. Use Dialog for tasks that must block the page, or Toast for transient status notifications.

Usage

'use client'
import { useRef } from 'react'
import {
  CookieConsent,
  readCookieConsent,
  type CookieConsentHandle,
} from '@uthereal/ui/cookie-consent'

export function PrivacyBanner() {
  const consentRef = useRef<CookieConsentHandle>(null)

  return (
    <>
      <button
        type="button"
        onClick={() => consentRef.current?.openPreferences()}
      >
        Cookie settings
      </button>

      <CookieConsent
        ref={consentRef}
        storageKey="site-cookie-consent"
        version="1"
        policy={{ label: 'Cookie policy', href: '/privacy' }}
        onChange={(value, detail) => {
          console.log(
            detail.action,
            value,
            readCookieConsent('site-cookie-consent', '1'),
          )
        }}
      />
    </>
  )
}

onChange receives the new category map (or null after reset()) and a detail object containing action ('accept-all' | 'reject-all' | 'save' | 'reset') and updatedAt. Your application enables or disables third-party scripts in response.

Examples

Surface faces

The same surface springs between the undecided consent bar, the expanded preferences panel, and the saved circular reopen button. Each preview below uses strategy="absolute" inside a bounded container.

Placement and custom categories

Anchor the bar to bottom-start or bottom-end, control which corner holds the reopen button with reopenSide, and supply only the categories your application uses.

Persistence and imperative control

Pass storageKey to persist the visitor's choice in localStorage as { value, version, updatedAt }. Increment version when your categories or policy change to re-prompt returning visitors. Call readCookieConsent(storageKey, version) anywhere, including during server rendering (where it returns null), to inspect the saved choice.

Attach a ref to invoke imperative methods from a footer link or account settings view:

MethodEffect
openPreferences()Opens the preferences panel and focuses its heading.
closePreferences()Closes the preferences panel without saving unsaved switch changes.
reset()Clears the saved choice (and storage entry) and re-opens the bar.

API reference

These serializable arguments and defaults come directly from the component schema.

ArgumentType / defaultDescription
categoriesCookieCategory[]Default: [{"id":"necessary","label":"Strictly necessary","description":"Sign-in, security, and your cart. The site can't work without these.","required":true,"defaultEnabled":true},{"id":"preferences","label":"Preferences","description":"Remember your language, region, and display settings.","required":false,"defaultEnabled":false},{"id":"analytics","label":"Analytics","description":"Count visits and see which pages help, only in aggregate.","required":false,"defaultEnabled":false},{"id":"marketing","label":"Marketing","description":"Measure campaigns and show relevant ads on other sites.","required":false,"defaultEnabled":false}]Up to ten cookie categories shown in the preferences panel. Required categories display "Always on" instead of a toggle; optional categories default to off.
defaultValueCookieConsentValue | nullDefault: nullInitial saved choice, or null when the visitor has not decided yet (showing the bar). Later argument edits do not reset a mounted instance.
defaultPreferencesOpenbooleanDefault: falseOpen the preferences panel on first render. Later argument edits do not reset a mounted instance.
policyCookieConsentPolicy—Optional link or action pointing to your privacy or cookie policy, rendered inline in both the bar and preferences panel.
positionbottom | bottom-start | bottom-endDefault: "bottom"Placement along the bottom edge: centered (bottom), inline start (bottom-start), or inline end (bottom-end).
strategyfixed | absoluteDefault: "fixed"fixed pins the surface to the viewport; absolute fills the nearest positioned container for embedded previews.
showReopenButtonbooleanDefault: trueKeep a 44 px circular reopen button after a choice is saved so visitors can revisit preferences.
reopenSidestart | end—Inline corner for the reopen button. Defaults to the bar side, or start when the bar is centered.
storageKeystring—Optional localStorage key that persists the choice across reloads. Read it elsewhere with readCookieConsent.
versionstringDefault: "1"Policy version stored alongside the saved choice. Bump it when categories change to re-prompt visitors.
labelsCookieConsentLabels—Visible copy and accessible labels for the bar, preferences panel, switches, and reopen button.
saveActionstring—Host-registered action name emitted through onAction when the visitor commits a choice.
recipestudio | softDefault: "studio"Visual treatment. Both recipes use the same interaction behavior.
themeCookieConsentTheme—Color mode, accent, core tokens, borderStrong, borderSubtle, and cookie-consent tokens (barRadius, panelRadius, listMaxHeight).
motionnone | subtle | expressiveDefault: "subtle"Animation preset. System reduced-motion preferences take precedence.
motionOptionsCookieConsentMotionOptions—Override the grow, shrink, and settle transitions. Durations are milliseconds.
dirltr | rtl—Reading direction. Omit it to inherit the page direction.

React integration

PropPurpose
refImperative CookieConsentHandle (openPreferences, closePreferences, reset).
value / onChange(value, detail)Controlled consent map (null = undecided) and commit/reset callback.
preferencesOpen / onPreferencesOpenChangeControlled preferences panel visibility.
onAction(action, itemId)Reports saveAction ('save') on commit and policy.action ('policy').
onPolicyClickReact click handler attached to the inline policy link or button.
presetApplication defaults merged below instance props.
tokensCSS variables applied after the typed theme on the surface and inner controls.
className / styleForwarded to the outer positioning layer.

Keyboard & accessibility

KeyInteraction
TabMoves across actions, the policy link, category switches, and the close button.
Space, EnterActivates buttons, opens preferences, or toggles the focused category switch.
EscapeCloses the preferences panel without saving and returns focus to the prior face.

Both the consent bar and preferences panel render as non-modal dialogs (role="dialog", aria-modal="false") so the page remains interactive. Opening preferences moves focus to the panel heading (tabIndex={-1}), closing returns focus to the reopen button (when decided) or the Customize button (when undecided), and saving moves focus to the reopen button when enabled. The Save choices button references a visually hidden summary of allowed optional categories through aria-describedby.

All layout offsets, alignment sides (bottom-start, bottom-end, reopenSide), and morph translation math mirror automatically under dir="rtl". Under forced-colors: active, the surface draws a CanvasText border and interactive controls keep Highlight focus outlines.

Motion and theming

On initial appearance after hydration, the surface rises 24 px from scale 0.98 on the smooth spring. Morphing between faces springs position, width, height, and border radius together: expanding transitions use visualSpring.morph and contracting transitions use visualSpring.smooth (zero overshoot). Faces crossfade in place with a 4 px blur and brief vertical settle.

Under prefers-reduced-motion: reduce, geometry jumps immediately and surfaces and faces crossfade with a 120 ms opacity fade. Setting motion="none" removes all transitions (0 ms).

theme accepts mode, accent, core and shape tokens, borderStrong, borderSubtle, and component tokens barRadius, panelRadius, and listMaxHeight. Buttons and switches inside the surface inherit recipe, mode, accent, motion, dir, and tokens.

Composition

In an agent composition, CookieConsent is a leaf component. Its committed choice persists in host state at /components/<id>/value (null until decided, then a category map reconciled against categories). Any saveAction or policy.action must name a host-registered action.

{
  "type": "CookieConsent",
  "props": {
    "strategy": "absolute",
    "policy": { "label": "Cookie policy", "href": "/privacy" },
    "saveAction": "save_cookie_preferences"
  }
}

On this page