UsefulKey

Keys

How keys work in UsefulKey. You can choose the default format, control the prefix, and specify a custom generator.

Built-in kinds

There are a few built-in key kinds that you can choose from.

  • KEY.URLSafe
    • Example: uk_
  • KEY.Hex
    • Example: uk_xxxxxxxxxx
  • KEY.Base32
    • Example: uk_xxxxxxxxxx
  • KEY.UUID
    • Example: uk_xxxxxxxxxx

You can use them anywhere in your code as they return a a string.

Here is an example setting the default key kind to KEY.URLSafe(40):

import { usefulkey, KEY } from 'betterkey';

const uk = usefulkey({ defaultKeyKind: KEY.URLSafe(40), keyPrefix: 'uk' });

Prefix control

The KEY functions allow you to optionally specify a prefix. The returned string will contain the prefix.

const key = KEY.URLSafe(40, 'coolPrefix');
// 'coolPrefix_xxxxxxxxxx'

Custom generation

It is possible to provide a totally custom generator to the UsefulKey instance. This is useful if you want to use a different format for your keys, or have specific requirments.

const uk = usefulkey({
  customGenerateKey: () => `${Date.now()}-${crypto.randomUUID()}`,
});

Security considerations

  • We recommend using a prefix for your keys. This helps you identify the source of the key.
  • You can specify a secret when you create the instance.This will use HMAC-SHA256 for hashing/verification.

General recommendations

  • Public APIs: URL-safe, random, 32–56 chars.
  • Internal services: Hex 32+ or URL-safe 32+.
  • Prefer stable prefixes per environment (e.g., uk, acme).