npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@jysperu/browser-cookie

v1.0.1

Published

Utilidades modernas para gestión de cookies en el navegador usando Cookie Store API

Readme

@jysperu/browser-cookie

npm version npm downloads License: MIT TypeScript Bundle Size

Utilidades modernas para gestión de cookies en el navegador usando la Cookie Store API.

🚀 Características

  • 🍪 Cookie Store API moderna y asíncrona
  • 🔧 TypeScript completamente tipado
  • Validaciones robustas de entrada
  • 🛡️ Manejo de errores comprehensivo
  • 📱 Compatibilidad con navegadores modernos
  • 🎯 API intuitiva y fácil de usar

📦 Instalación

npm install @jysperu/browser-cookie

⚡ Inicio Rápido

import { getCookie, setCookie, delCookie } from "@jysperu/browser-cookie";

// Obtener una cookie
const valor = await getCookie("mi-cookie");
console.log(valor); // "valor-de-la-cookie" o null

// Establecer una cookie
await setCookie("usuario", "juan123", {
  expiresInSeconds: 3600, // 1 hora
  path: "/",
  secure: true,
  sameSite: "strict",
});

// Eliminar una cookie
await delCookie("usuario");

📚 API Reference

🔍 getCookie

Obtiene una cookie por su nombre.

async function getCookie(name: string, returnValue?: boolean): Promise<string | CookieListItem | null>;

Parámetros:

  • name - Nombre de la cookie
  • returnValue - Si true retorna solo el valor, si false retorna el objeto completo (por defecto: true)

Ejemplos:

// Obtener solo el valor
const valor = await getCookie("session-id");
console.log(valor); // "abc123" o null

// Obtener objeto completo de la cookie
const cookie = await getCookie("session-id", false);
console.log(cookie);
// {
//   name: "session-id",
//   value: "abc123",
//   domain: "example.com",
//   ...
// }

🔧 setCookie

Establece una cookie con opciones configurables.

interface CookieOptions {
  expiresInSeconds?: number;
  path?: string;
  domain?: string;
  secure?: boolean;
  sameSite?: "strict" | "lax" | "none";
}

async function setCookie(name: string, value: string | null, options?: CookieOptions): Promise<CookieListItem | null>;

Parámetros:

  • name - Nombre de la cookie
  • value - Valor de la cookie (usar null para eliminar)
  • options - Opciones de configuración

Ejemplos:

// Cookie básica
await setCookie("usuario", "ana");

// Cookie con expiración
await setCookie("session", "xyz789", {
  expiresInSeconds: 1800, // 30 minutos
});

// Cookie segura para producción
await setCookie("auth-token", "token123", {
  expiresInSeconds: 86400, // 24 horas
  path: "/",
  secure: true,
  sameSite: "strict",
  domain: "miapp.com",
});

// Eliminar cookie (pasando null como valor)
await setCookie("old-cookie", null);

🗑️ delCookie

Elimina una cookie específica.

async function delCookie(name: string, path?: string): Promise<boolean>;

Parámetros:

  • name - Nombre de la cookie a eliminar
  • path - Ruta de la cookie (por defecto: "/")

Ejemplo:

// Eliminar cookie
const eliminada = await delCookie("session-id");
console.log(eliminada); // true si se eliminó correctamente

// Eliminar cookie de una ruta específica
await delCookie("user-prefs", "/dashboard");

📋 getCookies

Obtiene todas las cookies disponibles.

async function getCookies(url?: string): Promise<CookieListItem[]>;

Parámetros:

  • url - URL opcional para filtrar cookies

Ejemplo:

// Todas las cookies
const todasLasCookies = await getCookies();
console.log(todasLasCookies);

// Cookies de una URL específica
const cookiesEspecificas = await getCookies("https://api.miapp.com");

✅ cookieExists

Verifica si una cookie existe.

async function cookieExists(name: string): Promise<boolean>;

Ejemplo:

if (await cookieExists("usuario-logueado")) {
  console.log("Usuario está autenticado");
} else {
  console.log("Usuario necesita loguearse");
}

🧹 delCookies

Elimina todas las cookies del dominio actual.

async function delCookies(): Promise<number>;

Retorna: Número de cookies eliminadas

Ejemplo:

const eliminadas = await delCookies();
console.log(`Se eliminaron ${eliminadas} cookies`);

🎯 Casos de Uso Prácticos

Manejo de Sesión

import { getCookie, setCookie, delCookie } from "@jysperu/browser-cookie";

class SessionManager {
  private static SESSION_COOKIE = "user-session";

  static async login(userId: string, token: string) {
    await setCookie(this.SESSION_COOKIE, token, {
      expiresInSeconds: 86400, // 24 horas
      secure: true,
      sameSite: "strict",
      path: "/",
    });
  }

  static async getSession(): Promise<string | null> {
    return await getCookie(this.SESSION_COOKIE);
  }

  static async logout() {
    await delCookie(this.SESSION_COOKIE);
  }

  static async isLoggedIn(): Promise<boolean> {
    return await cookieExists(this.SESSION_COOKIE);
  }
}

Preferencias de Usuario

import { getCookie, setCookie } from "@jysperu/browser-cookie";

interface UserPreferences {
  theme: "light" | "dark";
  language: string;
  notifications: boolean;
}

class PreferencesManager {
  private static PREFS_COOKIE = "user-preferences";

  static async savePreferences(prefs: UserPreferences) {
    const prefsJson = JSON.stringify(prefs);
    await setCookie(this.PREFS_COOKIE, prefsJson, {
      expiresInSeconds: 365 * 24 * 3600, // 1 año
      path: "/",
    });
  }

  static async loadPreferences(): Promise<UserPreferences | null> {
    const prefsJson = await getCookie(this.PREFS_COOKIE);
    if (!prefsJson) return null;

    try {
      return JSON.parse(prefsJson);
    } catch {
      return null;
    }
  }

  static async resetPreferences() {
    await delCookie(this.PREFS_COOKIE);
  }
}

Sistema de Carrito de Compras

import { getCookie, setCookie } from "@jysperu/browser-cookie";

interface CartItem {
  id: string;
  name: string;
  price: number;
  quantity: number;
}

class ShoppingCart {
  private static CART_COOKIE = "shopping-cart";

  static async addItem(item: CartItem) {
    const cart = await this.getCart();
    const existingIndex = cart.findIndex((i) => i.id === item.id);

    if (existingIndex >= 0) {
      cart[existingIndex].quantity += item.quantity;
    } else {
      cart.push(item);
    }

    await this.saveCart(cart);
  }

  static async getCart(): Promise<CartItem[]> {
    const cartJson = await getCookie(this.CART_COOKIE);
    if (!cartJson) return [];

    try {
      return JSON.parse(cartJson);
    } catch {
      return [];
    }
  }

  private static async saveCart(cart: CartItem[]) {
    const cartJson = JSON.stringify(cart);
    await setCookie(this.CART_COOKIE, cartJson, {
      expiresInSeconds: 30 * 24 * 3600, // 30 días
      path: "/",
    });
  }

  static async removeItem(itemId: string) {
    const cart = await this.getCart();
    const updatedCart = cart.filter((item) => item.id !== itemId);
    await this.saveCart(updatedCart);
  }

  static async clearCart() {
    await delCookie(this.CART_COOKIE);
  }
}

🌐 Compatibilidad de Navegadores

La Cookie Store API es una tecnología moderna. Verifica la compatibilidad:

import { getCookie } from "@jysperu/browser-cookie";

// Verificar soporte
if (typeof window !== "undefined" && window.cookieStore) {
  // Usar las funciones normalmente
  const cookie = await getCookie("mi-cookie");
} else {
  // Fallback a document.cookie o mostrar mensaje
  console.warn("Cookie Store API no está disponible");
}

Navegadores soportados:

  • Chrome 87+
  • Edge 87+
  • Safari (soporte limitado)
  • Firefox (detrás de flag experimental)

🔒 Mejores Prácticas de Seguridad

// ✅ CORRECTO - Cookie segura para producción
await setCookie("auth-token", token, {
  secure: true, // Solo HTTPS
  sameSite: "strict", // Protección CSRF
  expiresInSeconds: 3600, // Expiración explícita
});

// ❌ INCORRECTO - Cookie insegura
await setCookie("auth-token", token); // Sin opciones de seguridad

Configuraciones Recomendadas

// Para tokens de autenticación
const authCookieOptions = {
  secure: true,
  sameSite: "strict" as const,
  expiresInSeconds: 1800, // 30 minutos
  path: "/",
};

// Para preferencias de usuario
const prefsCookieOptions = {
  sameSite: "lax" as const,
  expiresInSeconds: 365 * 24 * 3600, // 1 año
  path: "/",
};

// Para datos temporales
const tempCookieOptions = {
  sameSite: "lax" as const,
  expiresInSeconds: 900, // 15 minutos
  path: "/",
};

📦 Build y Distribución

# Construir el proyecto
npm run build

# Genera automáticamente:
# └── dist/
#     ├── cookie.esm.js     # ES Modules
#     ├── cookie.cjs.js     # CommonJS
#     ├── cookie.umd.js     # UMD
#     └── cookie.d.ts       # TypeScript definitions

🔗 Enlaces y Recursos

📄 Licencia

MIT License - Consulta el archivo LICENSE para detalles completos.

MIT License - Copyright (c) 2025 JYS Perú

Desarrollado con ❤️ por JYS Perú