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

@minimajs/cookie

v1.1.0

Published

Type-safe cookie management with validation and schema support

Readme

@minimajs/cookie

Type-safe cookie handling with validation for MinimaJS applications.

npm version License: MIT


Cookie Management

The @minimajs/cookie package provides a type-safe API for managing HTTP cookies in your MinimaJS application. Built on top of @fastify/cookie, it offers secure cookie handling with validation and signing support using TypeScript namespace merging.

Installation

npm install @minimajs/cookie

Setup

Register the cookie plugin with your MinimaJS application:

import { createApp } from "@minimajs/server";
import { plugin as cookiePlugin } from "@minimajs/cookie";

const app = createApp();

await app.register(cookiePlugin, {
  secret: "your-secret-key", // Required for signed cookies
  parseOptions: {}, // Optional parsing options
});

Basic Usage

The cookies() function returns all cookies, and provides namespace methods for getting, setting, and removing individual cookies:

import { cookies } from "@minimajs/cookie";

app.get("/example", () => {
  // Get all cookies
  const allCookies = cookies();
  // { "session-token": "abc123", "theme": "dark", ... }

  // Get a single cookie
  const sessionToken = cookies.get("session-token");

  // Set a cookie
  cookies.set("theme", "dark");

  // Remove a cookie
  cookies.remove("old-token");

  return { sessionToken };
});

API Reference

cookies<T>()

Returns all cookies as a record. Accepts an optional type parameter for type-safe access.

Type Parameter:

  • T (optional): Type definition for the cookies object (defaults to Record<string, string>)

Returns: T - All cookies as a typed record

Examples:

// Get all cookies (untyped)
const allCookies = cookies();
// Type: Record<string, string>

// Get all cookies with type parameter
interface MyCookies {
  sessionToken?: string;
  userId?: string;
  theme?: string;
}

const typedCookies = cookies<MyCookies>();
// Type: MyCookies
// Access with autocomplete: typedCookies.sessionToken

cookies.get(name, options?)

Retrieves a single cookie by name.

Parameters:

  • name (string): The cookie name
  • options (optional): Configuration object
    • required (boolean): If true, throws an error if the cookie doesn't exist
    • signed (boolean): If true, validates and unsigns the cookie

Returns: string | undefined (or string if required: true)

Examples:

// Get an optional cookie
const theme = cookies.get("theme");
// theme is string | undefined

// Get a required cookie (throws if not found)
const userId = cookies.get("user-id", { required: true });
// userId is string (guaranteed)

// Get a signed cookie
const sessionToken = cookies.get("session", {
  signed: true,
  required: true,
});

Error Codes:

  • COOKIE_NOT_FOUND: Thrown when a required cookie is missing
  • COOKIE_NOT_VALID: Thrown when a signed cookie validation fails

cookies.set(name, value, options?)

Sets a cookie with optional configuration.

Parameters:

  • name (string): The cookie name
  • value (string): The cookie value
  • options (optional): CookieSerializeOptions
    • domain (string): Cookie domain
    • path (string): Cookie path (default: "/")
    • maxAge (number): Max age in seconds
    • expires (Date): Expiration date
    • httpOnly (boolean): HTTP only flag
    • secure (boolean): Secure flag
    • sameSite ("strict" | "lax" | "none"): SameSite policy
    • signed (boolean): Sign the cookie

Example:

// Simple cookie
cookies.set("theme", "dark");

// Cookie with options
cookies.set("session-token", "abc123", {
  httpOnly: true,
  secure: true,
  maxAge: 3600, // 1 hour
  sameSite: "strict",
});

// Signed cookie
cookies.set("user-id", "12345", {
  signed: true,
  httpOnly: true,
});

// Cookie with expiration date
cookies.set("temp-token", "xyz789", {
  expires: new Date(Date.now() + 86400000), // 1 day
});

cookies.remove(name, options?)

Removes a cookie by setting its expiration to the past.

Parameters:

  • name (string): The cookie name
  • options (optional): Same as set() options (useful for matching path/domain)

Example:

// Remove a cookie
cookies.remove("session-token");

// Remove with specific path/domain
cookies.remove("session-token", {
  path: "/admin",
  domain: "example.com",
});

Advanced Usage

Type-Safe Cookies

Use TypeScript generics to get type-safe access to your cookies:

interface UserCookies {
  sessionId?: string;
  userId?: string;
  theme?: "light" | "dark";
  locale?: string;
}

app.get("/profile", () => {
  const userCookies = cookies<UserCookies>();

  // TypeScript autocomplete and type checking
  const theme = userCookies.theme; // Type: "light" | "dark" | undefined
  const sessionId = userCookies.sessionId; // Type: string | undefined

  return { theme };
});

Signed Cookies

Signed cookies provide tamper protection using HMAC signatures:

// Set a signed cookie
cookies.set("user-session", "sensitive-data", {
  signed: true,
  httpOnly: true,
});

// Get and validate a signed cookie
const session = cookies.get("user-session", {
  signed: true,
  required: true,
});
// Throws COOKIE_NOT_VALID if signature is invalid

Session Management Example

import { cookies } from "@minimajs/cookie";

// Login endpoint
app.post("/login", () => {
  // Authenticate user...
  const userId = "12345";

  // Set session cookie
  cookies.set("session", userId, {
    httpOnly: true,
    secure: true,
    signed: true,
    maxAge: 86400, // 24 hours
    sameSite: "strict",
  });

  return { success: true };
});

// Protected endpoint
app.get("/profile", () => {
  // Get session
  const userId = cookies.get("session", {
    signed: true,
    required: true,
  });

  // Fetch user data...
  return { userId };
});

// Logout endpoint
app.post("/logout", () => {
  cookies.remove("session");
  return { success: true };
});

Best Practices

  1. Use httpOnly for session cookies to prevent XSS attacks:

    cookies.set("session", token, { httpOnly: true });
  2. Use secure in production to ensure cookies are only sent over HTTPS:

    cookies.set("session", token, {
      secure: process.env.NODE_ENV === "production",
    });
  3. Sign sensitive cookies to prevent tampering:

    cookies.set("user-id", id, { signed: true });
  4. Set appropriate sameSite policies to prevent CSRF:

    cookies.set("session", token, { sameSite: "strict" });
  5. Use short maxAge for sensitive data:

    cookies.set("auth-token", token, { maxAge: 900 }); // 15 minutes

License

MIT

Links