Nanoid Custom Alphabet Short Identifiers

Generate compact, URL-safe identifiers with nanoid, sized from collision probability math instead of guesswork, with a custom alphabet option.

JavascriptData Integrity

Code

javascriptsnippet
16 lines
import { customAlphabet, nanoid } from 'nanoid';

const id = nanoid(21);

const shortUrl = customAlphabet('23456789ABCDEFGHJKLMNPQRSTUVWXYZ', 10);
const token = customAlphabet('0123456789abcdef', 32);

function collisionChance(bitsOfEntropy, generatedCount) {
  const probability = (generatedCount ** 2) / (2 ** (bitsOfEntropy + 1));
  return probability;
}

console.log('default id:', id);
console.log('short url code:', shortUrl());
console.log('hex token:', token());
console.log('collision chance:', collisionChance(126, 1e6));

What the code does

Nanoid Custom Alphabet Short Identifiers is built around the functions probability and collisionChance.

The import line is the dependency contract: customAlphabet, nanoid come from nanoid and nothing else.

What to watch for

  • Plan for an install step: nanoid is a real dependency, resolved by the package manager.

Using it

The main signature is written as const probability = (generatedCount ** 2)

Look for the default id:, short url code:, hex token: prefixes once the file starts running; each one ties a printed line to the step that produced it.

Key statements

const shortUrl = customAlphabet('23456789ABCDEFGHJKLMNPQRSTUVWXYZ', 10);
const probability = (generatedCount ** 2) / (2 ** (bitsOfEntropy + 1));
const token = customAlphabet('0123456789abcdef', 32);

Interactive Tools for This Topic

FAQ

Which packages must be installed first?
Yes. The imports resolve to `nanoid`, which the package manager must provide.