How to generate a NanoID
- A new 21-character ID appears at the top when the page loads. Press Copy, or the arrow for another.
- Set the Length and watch the collision figures: they show how many IDs you can safely create.
- Choose an Alphabet. No look-alikes drops characters people confuse, such as 0, O, 1, l and I, which helps for codes people type.
- Add a Prefix such as
usr_orord_to show what each ID is for, then copy or download up to 1,000.
How long should a NanoID be?
Each character adds log2(alphabet size) random bits: 6 bits for the default 64-character alphabet. The chance of a duplicate depends on how many IDs you make, not how fast. A rough guide for the default alphabet:
| Length | Random bits | IDs before a 1% chance of a duplicate | Good for |
|---|---|---|---|
| 8 | 48 | about 2.4 million | Short links, invite codes for a small app |
| 12 | 72 | about 9.7 billion | Public IDs in URLs for most apps |
| 16 | 96 | about 40 trillion | Large multi-tenant systems |
| 21 | 126 | about 1.3 × 1018 | Database keys and tokens, the library default |
Keep a unique index on the column anyway. It costs little and turns a once-in-a-lifetime collision into a clean error you can retry.
Why random IDs need rejection sampling
A random byte has 256 values. Taking it modulo an alphabet of, say, 62 characters makes the first 8 characters slightly more likely than the rest, which weakens the ID. This tool masks each byte to the next power of two (63 for a 62-character alphabet) and throws away values that don't map to a character, so every character has exactly the same chance.
Generate a NanoID in code
| Language | Package | Call |
|---|---|---|
| JavaScript / Node.js | nanoid | nanoid(), or customAlphabet("0123456789", 12)() |
| Python | nanoid | generate(size=21) |
| C# / .NET | Nanoid | Nanoid.Generate() |
| Go | github.com/matoous/go-nanoid/v2 | gonanoid.New() |
| Java | jnanoid | NanoIdUtils.randomNanoId() |
| Rust | nanoid | nanoid!() |