Last Updated: 3/12/2026
Basic Usage
Nanoid provides a simple API for generating unique IDs. By default, it generates 21-character URL-safe IDs using a secure random generator.
Generate an ID
import { nanoid } from 'nanoid'
const id = nanoid()
console.log(id) //=> "V1StGXR8_Z5jdHi6B-myT"The default 21-character ID provides collision probability similar to UUID v4.
Custom ID Size
Pass a size argument to generate shorter or longer IDs:
nanoid(10) //=> "IRFa-VaY2b"Important: Smaller IDs increase collision probability. Use the ID collision calculator to verify your ID size is safe for your use case.
Default Alphabet
Nanoid uses URL-friendly characters by default: A-Za-z0-9_- (64 characters total).
This alphabet is optimized for:
- URL safety (no encoding needed)
- Readability (avoids ambiguous characters)
- Compression efficiency (character order optimized for gzip/brotli)
Blocking Behavior
The default nanoid() function is synchronous and may briefly block the CPU while collecting entropy from the hardware random generator. For most applications, this is negligible.
If you need non-blocking ID generation or don’t require cryptographic security, see the Non-Secure guide.
Common Use Cases
Database primary keys:
const user = {
id: nanoid(),
name: 'Alice'
}File names:
const filename = `upload-${nanoid()}.jpg`API tokens (use longer IDs for security):
const token = nanoid(32)What’s Next
- Custom Alphabet & Size: Create IDs with custom characters
- Security Considerations: Understand Nanoid’s security guarantees
- CLI Reference: Generate IDs from the command line