UsefulKey
Simple, self-hosted API key generation and verification.
UsefulKey is a small, extensible library for generating, storing, verifying, and revoking API keys. It ships with a lightweight plugin system and swappable adapters for your infrastructure.
It can be used as a single in-process service in your app, or paired with your own HTTP layer to run a central key service. It's designed to be easy to use and extend, with a focus on simplicity and flexibility.
Features
- Key generation with prefixing
- Pluggable storage and rate limit backends (see Adapters)
- Plugins: rate limiting, IP access control, usage limits per key, permissions/scopes, enable/disable keys (see Plugins)
- Analytics for storing audit history and usage metrics
- Write your own plugins and adapters to extend the functionality with ease
Install
npm i usefulkey
At a glance
import { usefulKey, KEY, MemoryKeyStore, MemoryRateLimitStore, ConsoleAnalytics } from "betterkey";
import { enableDisablePlugin } from "usefulkey/plugins/enable-disable";
const uk = usefulKey(
{
// Each key will be prefixed with this string e.g. "uk_1234567890"
// Can be disabled with disablePrefix: true
keyPrefix: "uk",
// The default key kind to use when creating keys
// Can be overridden with keyKind on createKey (e.g. createKey({ keyKind: KEY.UUID() }))
// customGenerateKey can be used to override the default key generation logic
// customGenerateKey: (kind?: KeyKind) => string; // e.g. return "uk_" + crypto.randomUUID();
defaultKeyKind: KEY.URLSafe(40),
// Adapters are used to store and retrieve keys, rate limits, and log analytics
adapters: {
keyStore: new MemoryKeyStore(),
rateLimitStore: new MemoryRateLimitStore(),
analytics: new ConsoleAnalytics(),
},
},
{
// Plugins configured here will add additional functionality
plugins: [enableDisablePlugin()],
}
);
// Create a key
const { result: created } = await uk.createKey({ metadata: { plan: "pro" } });
console.log(created); // { id: "1234567890", key: "uk_1234567890", metadata: { plan: "pro" } }
// Verify the key exists and is not revoked, expired, etc.
const { result: verified } = await uk.verifyKey({
key: created!.key, // The key to verify
});
console.log(verified); // { valid: true, keyId: "1234567890", metadata: { plan: "pro" } }
For more information, see the API Reference for full function config options.
Continue with the Quick Start