npm package: @svnrnns/cookies
Description: Custom cookies API package built for TypeScript with Zod validation.
Author: svnrnns
Latest version: 1.0.0

# @svnrnns/cookies

A lightweight TypeScript library for managing browser cookies with type safety and optional **Zod** validation.

## Features

- **Type Safety**: Built for TypeScript with generic types
- **Optional Zod Validation**: Add schema validation when you need it
- **Fallback Values**: Ensure a value of the expected type is always retrieved
- **Safe Cookie Access**: Handles JSON parsing errors gracefully
- **Flexible Expiration**: Set expiration in days, hours, minutes, or "never"
- **Cookie Options**: Full support for path, domain, secure, and SameSite attributes

## Installation

```bash
npm install @svnrnns/cookies zod
```

## Quick Start

### Basic Usage

```ts
import { Cookies } from '@svnrnns/cookies';

// Set a cookie (defaults to 7 days expiration)
Cookies.setItem('theme', 'dark');
Cookies.setItem('user', { id: 1, name: 'John' }, { expires: 30 });

// Get a cookie (returns null if not found)
const theme = Cookies.getItem('theme'); // 'dark' | null
const user = Cookies.getItem<{ id: number; name: string }>('user');

// Get with fallback (returns fallback if not found)
const locale = Cookies.getItem('locale', 'en'); // 'en' if not found

// Remove a cookie
Cookies.removeItem('theme');

// Clear all cookies
Cookies.clearItems();

// Check if cookies are enabled
Cookies.isEnabled();
```

### With Zod Validation

Add a Zod schema as the third parameter for type-safe validation:

```ts
import { Cookies } from '@svnrnns/cookies';
import { z } from 'zod';

// Get with Zod validation (returns fallback if not found or invalid)
const themeSchema = z.enum(['light', 'dark']);
const theme = Cookies.getItem('theme', 'light', themeSchema);
// Returns 'light' if key 'theme' is not found or fails validation
```

### Standalone Functions

You can also import standalone functions:

```ts
import { setCookie, getCookie, removeCookie, clearCookies, isCookiesEnabled } from '@svnrnns/cookies';
```

## Examples

Store arrays or complex objects with Zod validation:

```ts
import { Cookies } from '@svnrnns/cookies';
import { z } from 'zod';

Cookies.setItem('filters', ['desc', 'price'], { expires: { hours: 2 } });

const schema = z.array(z.string());
const filters = Cookies.getItem('filters', [], schema);
// Returns ['desc', 'price'] or [] if invalid
```

Cookies can be set to never expire:

```ts
import { Cookies } from '@svnrnns/cookies';

Cookies.setItem('token', 'xxxx', { expires: 'never' });
```

Configure cookie options for advanced use cases:

```ts
import { Cookies } from '@svnrnns/cookies';

Cookies.setItem(
  'cookieConsent',
  { analytics: true, marketing: false },
  {
    path: '/',
    domain: '.example.com',
    secure: true,
    sameSite: 'Lax',
  }
);
```

## API Reference

### Cookies

| Method       | Signature                                                           | Description                                   |
| ------------ | ------------------------------------------------------------------- | --------------------------------------------- |
| `setItem`    | `setItem<T>(key: string, value: T, options?: CookiesOptions): void` | Stores a value in a cookie.                   |
| `getItem`    | `getItem<T>(key: string): T \| null`                                | Retrieves a value. Returns null if not found. |
| `getItem`    | `getItem<T>(key: string, fallback: T): T`                           | Retrieves a value with fallback.              |
| `getItem`    | `getItem<T>(key: string, fallback: T, schema: ZodType<T>): T`       | Retrieves a value with Zod validation.        |
| `removeItem` | `removeItem(key: string): void`                                     | Deletes a cookie by key.                      |
| `clearItems` | `clearItems(): void`                                                | Clears all cookies.                           |
| `isEnabled`  | `isEnabled(): boolean`                                              | Checks if cookies are enabled.                |

### CookiesOptions

| Option     | Type                                               | Default        | Description                                                                                      |
| ---------- | -------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------ |
| `expires`  | `number \| 'never' \| { days?, hours?, minutes? }` | `7`            | Expiration time: number of days, `'never'`, or an object with `days`, `hours`, and/or `minutes`. |
| `path`     | `string`                                           | `'/'`          | The URL path the cookie is valid for.                                                            |
| `domain`   | `string`                                           | Current domain | The domain the cookie is valid for.                                                              |
| `secure`   | `boolean`                                          | `undefined`    | When `true`, the cookie is only sent over HTTPS.                                                 |
| `sameSite` | `'Strict' \| 'Lax' \| 'None'`                      | `undefined`    | Controls cross-site request behavior.                                                            |

MIT License © 2025