API Reference

nanoid

Small, secure, URL-friendly unique ID generator for JavaScript with custom alphabets and configurable sizes for tokens and identifiers.

Official Documentation ↗
CompatibilityThis documentation covers version nanoid 5.x is ESM-first; CommonJS projects may need a compatible version or dynamic import. Check the official docs for the latest API surface.

Installation

npmnpm install nanoid
pnpmpnpm add nanoid
yarnyarn add nanoid

Methods

nanoid generates compact, URL-safe random IDs. It is a random string generator, not a complete identifier policy. Size, alphabet, uniqueness constraints, and storage decide whether an ID is safe for its purpose.

Entropy and size

Each character adds entropy based on the alphabet size. Short IDs are convenient but collide more often; handle collisions with a unique constraint and a bounded retry. For security tokens, use a size and storage design appropriate to the threat model, and store only a hash if the token is a bearer secret.

Human-readable IDs

For invite codes or short links, use customAlphabet to remove ambiguous characters and choose a length that balances usability and collision risk. Never derive security from obscurity alone; enforce expiry, revocation, and authorization.

Security notes

Quoted verbatim from the official documentation; this is not a complete threat model. 来源:https://cdn.jsdelivr.net/gh/ai/nanoid@latest/README.md · 取证方式:HTTP GET 官方 README/文档页(HTML 去标签) · 抓取时间:2026-11-07T13:51:03.068Z.

FAQ

Is nanoid cryptographically secure?
It uses the platform's cryptographically secure random source. It is suitable for identifiers and tokens when the size provides enough entropy, but it is not a password hashing function.
How long should an ID be?
It depends on the alphabet and the number of IDs. The default 21 characters with a 64-symbol alphabet gives strong collision resistance; shorter IDs are fine for small spaces but require collision handling.
Can I use nanoid for session tokens?
Yes, with a sufficient size and a secure transport and storage design. Store only a hash server-side if the token is a bearer credential, and set expiry and rotation.