UsefulKey

Quick Start

Start using UsefulKey in minutes. Configure adapters, add plugins, and see how each plugin changes the UsefulKey API.

Install

npm i usefulkey

Quick Start

Initialize UsefulKey

Configure adapters and defaults. Use in-memory adapters to get started quickly.

import { usefulkey, MemoryKeyStore, MemoryRateLimitStore, ConsoleAnalytics } from "betterkey";

const uk = usefulkey({
  keyPrefix: "uk",
  adapters: {
    keyStore: new MemoryKeyStore(),
    rateLimitStore: new MemoryRateLimitStore(),
    analytics: new ConsoleAnalytics(),
  },
});

Add plugins

Plugins add behavior and may extend the UsefulKey instance with new methods.

const ukWithPlugins = usefulkey(
  {
    keyPrefix: "uk",
    adapters: {
      keyStore: new MemoryKeyStore(),
      rateLimitStore: new MemoryRateLimitStore(),
      analytics: new ConsoleAnalytics(),
    },
  },
    plugins: [
      // Enable/disable keys
      enableDisable(), 

      // IP access control with a static allow list
      ipAccessControlStatic({ allow: ["1.1.1.1"] }), 

      // IP access control with a memory allow list that can be modified at runtime
      // uk.enableKey("0123456789") uk.disableKey("0123456789")
      ipAccessControlMemory(), 

      // Permissions/scopes
      permissionsScopes({ metadataKey: "scopes" }), 

      // Rate limit default for all verifyKey calls
      ratelimit({ default: { kind: "fixed", limit: 100, duration: "1m" } }), 

      // Usage limits per key
      usageLimitsPerKey(), 
    ],
  },
);

Use UsefulKey: basic create and verify

Use the UsefulKey instance to create and verify keys.


// Create a key
const { result: created2 } = await uk.createKey({ metadata: { plan: "free" } });

// Verify the key
const { result: verified2 } = await uk.verifyKey({ key: created2!.key });

// verified2 -> { valid: true, keyId: "...", metadata: { plan: "free" } }

Plugins overview and usage


Plugins vs Adapters

  • Plugins (features and policies)

    • Extend UsefulKey’s behavior without touching your infrastructure.
    • Run at specific lifecycle points (create/verify functions) to allow/deny or update state.
    • Can also add typed properties or helpers to the uk instance.
    • Examples: rate limiting, IP allow/deny, usage limits per key.
    • Choose them per instance when you call usefulkey(...).
  • Adapters (infrastructure backends)

    • Tell UsefulKey where and how to persist or send data.
    • Implement interfaces for your stack: KeyStoreAdapter, RateLimitStoreAdapter, AnalyticsAdapter.
    • Swap in Postgres/Redis/your own services instead of the default in-memory versions.
    • Choose them once at boot via the adapters option in usefulkey(...).

Quick mental model: Plugins decide what to do; Adapters decide where it goes.

For more, see the API Reference and individual plugin pages under Plugins.