ksuid.net
Back

nanoid generator

Recommended

Click on an ID to copy.

PropertyValue
Bit Length126
Output Length21 chars
Encodingbase64url
SortableNo
TimestampedNo
MonotonicNo
Crypto RandomYes

Nano ID is a tiny, secure, URL-friendly unique identifier generator created by Andrey Sitnik, a prolific open-source developer best known for authoring PostCSS and Autoprefixer. First released in 2017, Nano ID was designed to be a modern replacement for older ID generation libraries that either relied on insecure randomness, produced unnecessarily long output, or carried heavy dependency footprints. The library's core philosophy is minimalism: it provides cryptographically secure random identifiers in the smallest possible package, with sensible defaults that work for the vast majority of use cases while offering full customization for those who need it.

What set Nano ID apart from the start was its combination of small bundle size, cryptographic security, and URL-safe output. At approximately 130 bytes when minified and gzipped (for the non-secure version), Nano ID is one of the smallest ID generation libraries available, making it particularly attractive for frontend applications where bundle size directly impacts page load performance. Despite its tiny footprint, Nano ID does not compromise on security. It uses the Web Crypto API (crypto.getRandomValues()) in browsers and the crypto module in Node.js to source its randomness, ensuring that generated identifiers are cryptographically unpredictable. This stands in contrast to older libraries like ShortId, which relied on Math.random() and have since been deprecated in favor of Nano ID.

Nano ID has become one of the most popular ID generation libraries in the JavaScript ecosystem, with millions of weekly downloads on npm. It has also been ported to over two dozen programming languages, making it a genuinely cross-platform solution despite its JavaScript origins.

How Nano ID Works

Nano ID's generation algorithm is deliberately straightforward. At its core, the library generates a sequence of cryptographically secure random bytes and maps each byte to a character in a predefined alphabet. The result is a string of the desired length where every character is independently and uniformly selected from the alphabet.

The default alphabet consists of 64 URL-safe characters: A-Z, a-z, 0-9, -, and _. This alphabet was chosen because every character is safe for use in URLs, filenames, HTML attributes, and CSS selectors without encoding or escaping. The use of 64 characters means each character in the output encodes exactly 6 bits of entropy, making the relationship between string length and collision resistance easy to reason about.

The default length is 21 characters. With a 64-character alphabet, a 21-character Nano ID contains 126 bits of entropy (21 multiplied by 6), which is comparable to the 122 bits of randomness in a UUID v4. This means that at the default settings, Nano ID provides collision resistance on par with UUIDs while producing a shorter, cleaner string without hyphens or fixed structural elements.

The randomness source is the critical security component. In browser environments, Nano ID calls crypto.getRandomValues(), which is part of the Web Crypto API. In Node.js, it uses the built-in crypto.randomBytes() function. Both sources are backed by operating system-level entropy pools and are suitable for security-sensitive applications. The library also provides a non-secure variant that uses Math.random() for environments where maximum performance is the priority, though this variant is generally discouraged for production use.

One of Nano ID's most powerful features is its customizability. Developers can configure both the alphabet and the length of generated identifiers. A custom alphabet might use only lowercase letters and digits for case-insensitive systems or only numeric characters for PIN-like codes. When using custom alphabets that are not a power of two in size, Nano ID applies a rejection sampling technique to ensure uniform character distribution, preventing statistical biases that could reduce effective entropy.

The length parameter allows developers to balance collision resistance against string compactness. Shorter identifiers (such as 10 or 12 characters) are suitable for smaller namespaces, while longer identifiers (24 or more characters) provide additional safety margins for large-scale systems.

Unlike time-sortable formats, Nano ID identifiers contain no embedded timestamp or structural information. They are purely random, which means they cannot be sorted by creation time and reveal nothing about when or where they were generated. Applications that need chronological ordering must maintain a separate timestamp field.

Use Cases

Frontend application state management. Nano ID is widely used in React, Vue, and other frontend frameworks for generating unique keys for list items, form fields, and component instances. Its tiny bundle size means it adds negligible overhead to client-side applications, and its cryptographic security ensures that generated keys are unpredictable, which matters in contexts where identifiers are exposed in the DOM or transmitted to servers.

URL shorteners and shareable links. The URL-safe default alphabet makes Nano ID a natural fit for generating short, shareable identifiers for URL shortening services, file-sharing links, and invitation codes. By adjusting the length parameter, developers can produce identifiers as short as 8 to 10 characters for human-friendly URLs while maintaining acceptable collision resistance for their expected namespace size.

Database record identifiers. For applications that do not require time-sortable primary keys, Nano ID provides a lightweight alternative to UUIDs. The shorter default output (21 characters versus 36 for a UUID) saves storage space and improves readability in logs and debugging sessions. In PostgreSQL, MySQL, and other relational databases, Nano ID strings can be stored efficiently in VARCHAR or TEXT columns, and their randomness distributes writes evenly across B-tree indexes.

Temporary tokens and nonce values. Nano ID's cryptographic security makes it suitable for generating temporary authentication tokens, email verification codes, password reset links, and cryptographic nonces. While purpose-built security libraries are preferred for high-stakes authentication flows, Nano ID provides a strong foundation for ephemeral identifiers where unpredictability is the primary requirement.

Comparison with Alternatives

Compared to UUID v4, Nano ID produces shorter, more compact identifiers (21 characters versus 36) with comparable collision resistance (126 bits of entropy versus 122 bits). UUID v4 strings contain hyphens and fixed version/variant bits that make them immediately recognizable but also longer and less URL-friendly. UUID v4 benefits from universal standardization and native support in virtually every database and programming language, while Nano ID offers a more developer-friendly output format and a significantly smaller library footprint. For new applications that do not require UUID format compatibility, Nano ID is often the more practical choice.

Compared to CUID2, Nano ID is a purely random generator with no internal structure, while CUID2 incorporates a timestamp and counter into its hash-based generation process. Both produce URL-safe, lowercase-compatible strings with strong collision resistance. Nano ID's key advantages are its smaller bundle size, full customizability of alphabet and length, and availability in over two dozen programming languages. CUID2 offers an opinionated, zero-configuration experience with the guarantee that its first character is always a letter. Developers who need maximum flexibility tend to prefer Nano ID, while those who want a secure default with no decisions to make may prefer CUID2.

Compared to ShortId, Nano ID is its direct spiritual successor. ShortId was once the most popular short ID library in the JavaScript ecosystem, but it has been deprecated by its maintainer, who now recommends Nano ID as a replacement. ShortId relied on Math.random() for its randomness, making it unsuitable for security-sensitive applications, and produced identifiers with less uniform distribution. Nano ID addresses all of these shortcomings with cryptographically secure randomness, a URL-safe default alphabet, and uniform distribution, all in a smaller package.

Code Examples

import { nanoid } from 'nanoid';
const id = nanoid();
console.log(id); // ~21 chars

Frequently Asked Questions

What is Nano ID?

Nano ID is a tiny, secure, URL-friendly unique string ID generator for JavaScript and many other programming languages. It uses cryptographically strong random APIs to produce compact identifiers that are suitable for URLs, HTML IDs, database keys, and any context where short, unique strings are needed.

Is Nano ID cryptographically secure?

Yes, Nano ID uses the Web Crypto API (crypto.getRandomValues) in browsers and the crypto module in Node.js to generate random bytes. This ensures that generated IDs are unpredictable and safe to use in security-sensitive contexts where guessable IDs could be exploited.

How does Nano ID compare to UUID?

Nano ID produces shorter identifiers than UUID while maintaining comparable collision resistance. A default 21-character Nano ID has roughly the same number of unique possibilities as a 36-character UUID v4. Nano ID is also more URL-friendly since it avoids special characters like hyphens by default.

Can I customize Nano ID length?

Yes, Nano ID allows you to specify a custom length for generated IDs. Shorter IDs are more compact but have higher collision probability, while longer IDs provide greater uniqueness guarantees. You can also define a custom alphabet to control exactly which characters appear in the output.

What alphabet does Nano ID use?

By default, Nano ID uses a URL-safe alphabet of 64 characters: A-Z, a-z, 0-9, underscore, and hyphen. This alphabet is optimized for compactness and URL safety. A custom alphabet function is also available if you need to restrict or expand the character set for your use case.

Comparisons Featuring NANOID

Related Generators

© 2024 Carova Labs. All rights reserved