@adalink/spark-cookie
v1.0.0
Published
Cookie utilities for web development
Maintainers
Readme
🍪 Spark Cookie
Cookie utilities for web development. Zero dependencies, tree-shakeable.
📖 What is Spark Cookie?
Spark Cookie is a modern, lightweight library for managing browser cookies with a clean, simple API. Built on native Web Platform APIs, it provides powerful utilities for creating, reading, and updating cookies without framework overhead.
🎯 Why Choose Spark Cookie?
- Zero Dependencies - No runtime dependencies, just pure Web Platform APIs
- Simple API - Clean, intuitive interface for cookie operations
- Framework Agnostic - Works with any framework or vanilla JavaScript
- Performance First - Minimal bundle size (~300B)
- Developer Experience - Automatic URL encoding/decoding
- Production Ready - Battle-tested in real-world applications
🚀 Perfect For
- Web Components Projects - Manage cookies in custom elements
- Progressive Enhancement - Build on web standards
- Performance-Critical Apps - Minimal overhead, maximum speed
- Cross-Framework Projects - Consistent cookie management
- Authentication - Secure cookie handling
✨ Key Features
🍪 Simple API
Handle cookies with ease:
import cookie from '@adalink/spark-cookie';
// Set a cookie
cookie.setItem('theme', 'dark');
// Get a cookie
const theme = cookie.getItem('theme');
console.log(theme); // 'dark'🔐 Secure Options
Full support for modern cookie security:
import cookie from '@adalink/spark-cookie';
// Secure cookie with all options
cookie.setItem('session', 'abc123', {
expires: new Date('2026-12-31'),
maxAge: 3600,
domain: '.example.com',
path: '/',
secure: true,
httpOnly: true,
sameSite: 'strict'
});⚡ Automatic Encoding
URL encoding and decoding handled automatically:
// Values with special characters
cookie.setItem('name', ' João Silva');
const value = cookie.getItem('name');
// ' João Silva'🔗 Integração com Spark Ecosystem
O Spark Cookie é parte do Spark Ecosystem, trabalhando em harmonia com outras bibliotecas Spark para criar aplicações web completas.
📦 Pacotes Relacionados
@adalink/spark-std - Biblioteca padrão com decorators para Web Components
Use Spark Cookie para gerenciar cookies em componentes criados com Spark Std:
import { define, connected, disconnected } from '@adalink/spark-std';
import { paint, html, css } from '@adalink/spark-std/dom';
import { event } from '@adalink/spark-std/event';
import cookie from '@adalink/spark-cookie';
@define('spark-theme-switcher')
@paint(template, styles)
class ThemeSwitcher extends HTMLElement {
#currentTheme = 'light';
connectedCallback() {
// Load theme from cookie
const savedTheme = cookie.getItem('theme');
if (savedTheme) {
this.#currentTheme = savedTheme;
}
this.updateTheme();
}
@event.click('button')
toggleTheme() {
this.#currentTheme = this.#currentTheme === 'light' ? 'dark' : 'light';
// Save theme to cookie
cookie.setItem('theme', this.#currentTheme, {
expires: new Date(Date.now() + 365 * 24 * 60 * 60 * 1000),
path: '/'
});
this.updateTheme();
}
updateTheme() {
this.dispatchEvent(new CustomEvent('theme-changed', {
detail: this.#currentTheme,
bubbles: true,
composed: true
}));
}
}
function template(component) {
return html`
<button class="theme-toggle">
Current theme: ${component.#currentTheme}
</button>
`;
}
function styles(component) {
return css`
.theme-toggle {
padding: 0.5rem 1rem;
background: #667eea;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
.theme-toggle:hover {
background: #764ba2;
}
`;
}Funcionalidades Combinadas:
- ✅ Spark Std fornece decorators (
@define,@paint,@event) - ✅ Spark Cookie fornece gerenciamento de cookies
- ✅ Use decorators para definir comportamento do componente
- ✅ Use cookies para persistir configurações entre sessões
- ✅ Ambos funcionam com Web Components nativos
Ecosystem Diagram:
┌─────────────────────────────────────────────────────┐
│ Application Layer │
└───────────────────┬─────────────────────────────────┘
│
┌───────────────────▼─────────────────────────────────┐
│ Spark Framework Layer │
│ ┌──────────────────────────────────────────────┐ │
│ │ @adalink/spark-std │ │
│ │ ┌──────────┐ ┌─────┐ ┌────────┐ │ │
│ │ │Directive │ │ DOM │ │ Event │ │ │
│ │ └──────────┘ └─────┘ └────────┘ │ │
│ └──────────────────────────────────────────────┘ │
│ ┌──────────────────────────────────────────────┐ │
│ │ @adalink/spark-cookie │ │
│ │ ┌──────────┐ ┌──────────┐ │ │
│ │ │ getItem │ │ setItem │ │ │
│ │ └──────────┘ └──────────┘ │ │
│ └──────────────────────────────────────────────┘ │
└───────────────────┬─────────────────────────────────┘
│
┌───────────────────▼─────────────────────────────────┐
│ Web Platform APIs │
│ document.cookie API │
└─────────────────────────────────────────────────────┘🚀 Quick Start
Installation
Option 1: Install from npm (Recommended)
# Using npm
npm install @adalink/spark-cookie
# Using yarn
yarn add @adalink/spark-cookie
# Using pnpm
pnpm add @adalink/spark-cookie
# Using bun
bun add @adalink/spark-cookieOption 2: Install from GitHub (Alternative)
# Install directly from GitHub repository
npm install github:Adalink-ai/spark_cookie#v1.0.0Option 3: Import from CDN (Browser Only)
// Import modules from unpkg or jsDelivr (ESM)
import cookie from "https://unpkg.com/@adalink/[email protected]/dist/cookie.js";⚠️ Important Notice: This package is private and published to npm. To install it:
- Have an npm account
- Request access to the
@adalinkscope from the maintainers - Configure npm authentication in your environment
Installation Options:
- npm registry (recommended) - Requires npm authentication and scope access
- GitHub (alternative) - Works without npm authentication, installs directly from repository
- CDN (browser only) - Import modules directly from unpkg or jsDelivr, no build step required
Basic Usage
Setting Cookies
// Simple cookie
cookie.setItem('theme', 'dark');
// Cookie with expiration (7 days)
cookie.setItem('session', 'abc123', {
expires: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
});
// Cookie with max-age (1 hour)
cookie.setItem('token', 'xyz789', {
maxAge: 3600
});Getting Cookies
// Get a cookie
const theme = cookie.getItem('theme');
console.log(theme); // 'dark' or null if not found
// Handle missing cookies
const session = cookie.getItem('session');
if (!session) {
// Handle missing session
}Secure Cookies
// Secure cookie (HTTPS only)
cookie.setItem('token', 'secure-token', {
secure: true
});
// HTTP-only cookie (not accessible via JavaScript)
cookie.setItem('session', 'session-id', {
httpOnly: true
});
// SameSite cookie (prevents CSRF)
cookie.setItem('user', 'user-id', {
sameSite: 'strict' // or 'lax' or 'none'
});
// Combined security options
cookie.setItem('auth', 'auth-token', {
secure: true,
httpOnly: true,
sameSite: 'strict',
expires: new Date(Date.now() + 24 * 60 * 60 * 1000)
});Domain and Path
// Cookie for entire domain
cookie.setItem('language', 'pt-BR', {
domain: '.example.com',
path: '/'
});
// Cookie for specific path
cookie.setItem('preference', 'value', {
path: '/app/settings'
});Deleting Cookies
// Delete by setting max-age to 0
cookie.setItem('theme', '', {
maxAge: 0
});
// Delete with domain/path matching
cookie.setItem('session', '', {
domain: '.example.com',
path: '/',
maxAge: 0
});📦 API Reference
cookie.getItem(name)
Retrieves a cookie value by name.
Parameters:
name(string) - Name of the cookie
Returns:
string | null- Cookie value or null if not found
Example:
const value = cookie.getItem('session');
if (value !== null) {
console.log('Session:', value);
}cookie.setItem(name, value, options?)
Creates or updates a cookie.
Parameters:
name(string) - Name of the cookievalue(string) - Value to storeoptions(object, optional)expires(Date) - Expiration datemaxAge(number) - Max age in secondsdomain(string) - Cookie domainpath(string) - Cookie pathsecure(boolean) - HTTPS onlyhttpOnly(boolean) - Not accessible via JavaScriptsameSite(string) -'lax','strict', or'none'
Example:
cookie.setItem('theme', 'dark', {
expires: new Date('2026-12-31'),
path: '/'
});🎯 Real-World Use Cases
Theme Persistence
import cookie from '@adalink/spark-cookie';
function saveTheme(theme) {
cookie.setItem('theme', theme, {
expires: new Date(Date.now() + 365 * 24 * 60 * 60 * 1000),
path: '/'
});
}
function loadTheme() {
return cookie.getItem('theme') || 'light';
}
// Usage
const currentTheme = loadTheme();
document.documentElement.setAttribute('data-theme', currentTheme);Session Management
import cookie from '@adalink/spark-cookie';
function createSession(userId, duration = 3600) {
const sessionId = generateSessionId();
cookie.setItem('session', sessionId, {
maxAge: duration,
httpOnly: true,
secure: true,
sameSite: 'strict'
});
return sessionId;
}
function getSession() {
return cookie.getItem('session');
}
function destroySession() {
cookie.setItem('session', '', {
maxAge: 0
});
}User Preferences
import cookie from '@adalink/spark-cookie';
const prefs = {
setLanguage(lang) {
cookie.setItem('language', lang, {
expires: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
path: '/'
});
document.documentElement.lang = lang;
},
getLanguage() {
return cookie.getItem('language') || 'en';
},
setTimezone(tz) {
cookie.setItem('timezone', tz, {
expires: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
path: '/'
});
document.documentElement.dataset.timezone = tz;
},
getTimezone() {
return cookie.getItem('timezone') || 'UTC';
}
};
// Usage
prefs.setLanguage('pt-BR');
prefs.setTimezone('America/Sao_Paulo');📊 Why Spark Cookie Over Alternatives?
| Feature | Spark Cookie | js-cookie | Cookie.js | |---------|--------------|-----------|-----------| | Zero Dependencies | ✅ | ✅ | ✅ | | Bundle Size | ~300B | ~1.2KB | ~800B | | Auto Encoding | ✅ | ✅ | ✅ | | Secure Options | ✅ | ✅ | ⚠️ | | SameSite Support | ✅ | ✅ | ❌ | | Interface | Modern | Callback-based | Callback-based | | TypeScript Ready | ✅ | ✅ | ❌ |
🌐 Usage in Frameworks
With React
import cookie from '@adalink/spark-cookie';
function ThemeToggle() {
const [theme, setTheme] = React.useState(() =>
cookie.getItem('theme') || 'light'
);
const toggle = () => {
const newTheme = theme === 'light' ? 'dark' : 'light';
setTheme(newTheme);
cookie.setItem('theme', newTheme);
};
return <button onClick={toggle}>{theme}</button>;
}With Vue
import cookie from '@adalink/spark-cookie';
export default {
data() {
return {
theme: cookie.getItem('theme') || 'light'
}
},
methods: {
toggleTheme() {
this.theme = this.theme === 'light' ? 'dark' : 'light';
cookie.setItem('theme', this.theme);
}
}
}🛠️ Development
Prerequisites
- Node.js 18+
Setup
# Clone repository
git clone https://github.com/Adalink-ai/spark_cookie.git
cd spark_cookie
# Install dependencies
npm install
# Build package
npm run build
# Start development server
npm run dev
# Lint and format
npx biome check .
npx biome check --write .📚 Documentation
- Architecture: ARCHITECTURE.md - Design decisions and patterns
- Contributing: CONTRIBUTING.md - Development guidelines
- Security: SECURITY.md - Security policies
- Changelog: CHANGELOG.md - Project changes
- Authors: AUTHORS.md - Author information
🤝 Contributing
We welcome contributions! Please read our Contributing Guide before getting started.
Ways to contribute:
👥 Author & Community
Cleber de Moraes Goncalves - Creator & Lead Maintainer
- 📧 Email: [email protected]
- 🐙 GitHub: deMGoncalves
- 💼 LinkedIn: deMGoncalves
- 📸 Instagram: deMGoncalves
🌟 Star the Project
If you find Spark Cookie useful, please ⭐ star it on GitHub!
📢 Share
Share Spark Cookie with your network:
🌐 Spark Ecosystem
O Spark Ecosystem é um conjunto de bibliotecas para desenvolvimento web reativo:
- @adalink/spark-std - Biblioteca padrão com decorators para Web Components
- @adalink/spark-echo - Sistema de comunicação reativa entre componentes
Mais pacotes em breve:
- @adalink/spark-form - Componentes de formulário reativos (em breve)
- @adalink/spark-router - Roteamento SPA (em breve)
📄 License
Apache-2.0 © 2026 Adalink
🔗 Links
- Repository: github.com/Adalink-ai/spark_cookie
- NPM Package: npmjs.com/package/@adalink/spark-cookie
- Organization: github.com/Adalink-ai
Built with ❤️ by Adalink
Spark Cookie - Manage cookies with ease. 🍪
