@bliztek/consent
v1.0.0
Published
Headless, zero-dependency cookie consent hook and types for React. GDPR-ready with granular per-category controls.
Maintainers
Readme
@bliztek/consent
Headless, zero-dependency cookie consent hook and types for React. GDPR-ready with granular per-category controls.
Features
- Zero runtime dependencies — only
reactas a peer dep - Headless — bring your own UI, this package handles state and persistence
useConsenthook — localStorage persistence, legacy migration, accept/reject/save- 4 cookie categories: Necessary (locked on), Analytics, Marketing, Functional
- Input validation —
isConsentPreferences()type guard validates localStorage data shape, rejects malformed values - TypeScript-first — full type exports for
ConsentPreferences,ConsentCategory, etc. - SSR-safe — reads localStorage in
useEffect, no hydration mismatches - ESM + CJS — dual module build with proper
exportsfield and tree-shaking support
Install
npm install @bliztek/consentPeer dependency:
npm install reactQuick Start
import { useConsent } from "@bliztek/consent";
function App() {
const {
preferences,
acceptAll,
rejectAll,
setPreferences,
showPreferencesPanel,
setShowPreferencesPanel,
initialized,
} = useConsent();
// Don't render until localStorage has been read
if (!initialized) return null;
// No stored preferences — show a consent banner
if (!preferences) {
return (
<div role="alertdialog" aria-label="Cookie consent">
<p>We use cookies to improve your experience.</p>
<button onClick={acceptAll}>Accept all</button>
<button onClick={rejectAll}>Reject all</button>
<button onClick={() => setShowPreferencesPanel(true)}>
Manage cookies
</button>
</div>
);
}
return <main>{/* your app */}</main>;
}API
useConsent(options?)
import { useConsent } from "@bliztek/consent";Options
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| storageKey | string | "cookiePreferences" | localStorage key for persisted preferences |
| legacyKey | string | -- | If set, migrates a legacy "granted"/"denied" value to the new format |
Return value
| Property | Type | Description |
|----------|------|-------------|
| preferences | ConsentPreferences \| null | Current consent state, or null if no choice has been made |
| setPreferences | (prefs: ConsentPreferences) => void | Save granular preferences (persists to localStorage, closes preferences panel) |
| acceptAll | () => void | Grant all categories (persists to localStorage, closes preferences panel) |
| rejectAll | () => void | Deny all optional categories (persists to localStorage, closes preferences panel) |
| showPreferencesPanel | boolean | UI state for toggling a preferences modal |
| setShowPreferencesPanel | (show: boolean) => void | Toggle the preferences panel state |
| initialized | boolean | true once localStorage has been read (safe to render) |
isConsentPreferences(value)
Type guard that validates whether a value conforms to the ConsentPreferences shape. Used internally to reject malformed localStorage data. Also exported for consumer use.
import { isConsentPreferences } from "@bliztek/consent";
const raw = JSON.parse(localStorage.getItem("myKey") ?? "null");
if (isConsentPreferences(raw)) {
// raw is ConsentPreferences
}Types
type ConsentCategory = "necessary" | "analytics" | "marketing" | "functional";
type ConsentPreferences = {
necessary: true; // always true, not toggleable
analytics: boolean;
marketing: boolean;
functional: boolean;
};Constants
| Constant | Description |
|----------|-------------|
| CONSENT_CATEGORIES | Array of { key, label, description, locked } for all 4 categories |
| ALL_GRANTED | All categories set to true |
| ALL_DENIED | Only necessary: true, rest false |
Error Handling
This library is designed to be resilient in hostile browser environments:
- localStorage unavailable (SSR, private browsing, storage disabled): All read/write operations are wrapped in try/catch. The hook initializes with
preferences: nullandinitialized: true, so your UI renders correctly. - localStorage quota exceeded: Persistence silently fails, but in-memory state still updates. The user's session works normally; preferences just won't survive a page reload.
- Malformed localStorage data: If another script writes garbage to the storage key,
isConsentPreferences()rejects it and the hook returnsnull— prompting the user to make a fresh choice.
No errors are thrown to the consumer. All failure modes result in preferences: null.
Integrating with Google Analytics
import { useConsent } from "@bliztek/consent";
function AnalyticsLoader() {
const { preferences } = useConsent();
if (!preferences?.analytics) return null;
return <script src="https://www.googletagmanager.com/gtag/js?id=G-XXXXX" />;
}Legacy Migration
If you previously stored consent as a single "granted" / "denied" string, pass the old key to legacyKey:
const consent = useConsent({
legacyKey: "userConsent", // old key — will be read, migrated, and removed
});On first load, the hook will:
- Check
localStoragefor the newstorageKey(default"cookiePreferences") - If not found, check
legacyKey - Map
"granted"toALL_GRANTED,"denied"toALL_DENIED - Write the migrated value to the new key and remove the legacy key
Contributing
Contributions are welcome! If you'd like to improve this package:
- Fork the repository.
- Create a new branch:
git checkout -b feature-name - Make your changes and commit:
git commit -m "Add new feature" - Push your branch and open a Pull Request.
More Information
This package is built and maintained by Bliztek. We design and develop customized websites and web applications to help businesses of all sizes achieve their goals. Our solutions prioritize scalability, security, and performance to drive growth and ensure long-term success.
- Follow @Dev4TheWeb on Twitter/X for updates from the creator
- Follow @Bliztek on Twitter/X for updates from the company side
- Read our Company blog to learn more about our contributions to open source!
License
This package is licensed under the MIT License.
