A tiny (118 bytes), secure URL-friendly unique string ID generator
nanoid is a minimalist unique identifier generator that produces secure, URL-safe strings for JavaScript applications. At only 118 bytes, it's designed for developers who need reliable ID generation without the bloat of traditional UUID libraries. The package generates 21-character IDs by default using a 64-symbol alphabet (A-Za-z0-9_-), providing collision resistance comparable to UUID v4 while using significantly fewer characters.
Unlike alternatives that rely on Math.random() or complex algorithms, nanoid uses hardware random number generators through Node.js crypto module and the Web Crypto API in browsers. This cryptographic approach ensures unpredictability, making IDs suitable for security-sensitive applications. The package has achieved massive adoption with over 93 million weekly downloads, driven by modern frameworks and tools that prioritize bundle size optimization.
The library's architecture is deliberately simple: zero dependencies, cross-platform support, and a straightforward API that works identically in Node.js and browsers. This simplicity reduces supply chain vulnerabilities and makes it trivial to audit. For applications generating thousands of IDs per second, nanoid's performance (3.6M ops/sec) far exceeds alternatives like shortid while maintaining the security guarantees developers expect from production-grade ID generators.
nanoid solves the common problem of generating unique identifiers efficiently without forcing developers to choose between security, performance, and bundle size. It's particularly relevant in modern web development where every kilobyte matters for page load times, and where developers need IDs that work seamlessly in URLs, databases, and APIs without encoding issues.
import { nanoid, customAlphabet } from 'nanoid';
// Basic usage: generate URL-safe ID
const userId = nanoid();
console.log(userId); // 'V1StGXR8_Z5jdHi6B-myT'
// Generate shorter ID (higher collision risk)
const shortId = nanoid(10);
console.log(shortId); // 'IRFa-VaY2b'
// Custom alphabet for specific use cases
const numericId = customAlphabet('0123456789', 12);
const orderId = numericId();
console.log(orderId); // '385938925038'
// Hex IDs for legacy system compatibility
const hexId = customAlphabet('0123456789ABCDEF', 16);
const deviceId = hexId();
console.log(deviceId); // '3A9F5B2C8D1E4F7A'
// Real-world example: generate database records
const createUser = async (email) => {
const user = {
id: nanoid(),
email,
sessionToken: nanoid(32),
createdAt: Date.now()
};
// await db.users.insert(user);
return user;
};
const newUser = await createUser('user@example.com');
console.log(newUser);Database primary keys: Use nanoid to generate readable, URL-friendly primary keys for databases like MongoDB, PostgreSQL, or DynamoDB. Unlike auto-incrementing integers, nanoid IDs don't expose record counts and work well in distributed systems without coordination.
File upload identifiers: Generate unique filenames for user uploads to cloud storage services (S3, GCS) where collision resistance is critical and filenames must be URL-safe without percent-encoding.
Session tokens and tracking IDs: Create unpredictable session identifiers for authentication systems or tracking IDs for analytics events where security matters but you need something shorter than traditional UUIDs.
Short URLs and slugs: Build URL shortener services or generate unique slugs for articles, products, or resources where you want compact, collision-resistant identifiers that look clean in browser address bars.
API request IDs: Implement request correlation IDs for distributed systems and microservices logging, where you need to trace requests across services without the verbosity of full UUIDs cluttering your logs.
npm install nanoidpnpm add nanoidbun add nanoid