Last updated
What is NanoID?
NanoID is a tiny, secure, URL-friendly unique string ID generator for JavaScript. Created as a modern alternative to UUID, NanoID is 60% smaller than UUID (21 characters vs 36), twice as fast, and uses a larger alphabet for better security. It's used by popular projects like Next.js, React, Vercel, and many others.
Unlike UUIDs which use hexadecimal encoding (0-9, a-f), NanoID uses a URL-safe alphabet (A-Za-z0-9_-) by default, making it perfect for use in URLs, file names, and anywhere you need a compact, unique identifier. The default length of 21 characters provides the same collision probability as UUID v4 (2^128) but in a much shorter string.
NanoID Structure
A NanoID is a random string generated using cryptographically secure random number generation. The default configuration uses:
- Alphabet: A-Za-z0-9_- (64 characters, URL-safe)
- Length: 21 characters (customizable)
- Randomness: Cryptographically secure (uses crypto.getRandomValues)
- Collision probability: Same as UUID v4 with default settings
Length: 21 characters
Alphabet: URL-safe (A-Za-z0-9_-)
Use case: Perfect for URLs, database IDs, file names
Why Use NanoID Instead of UUID?
NanoID offers several advantages over traditional UUIDs:
- Smaller: 21 characters vs 36 characters (60% reduction)
- Faster: 2x faster generation than UUID
- More secure: Larger alphabet (64 vs 16 characters)
- URL-safe: No special characters that need encoding
- Customizable: Adjust length and alphabet to your needs
- Portable: Available in 20+ programming languages
NanoID vs UUID Comparison
| Feature | NanoID | UUID v4 |
|---|---|---|
| Length | 21 characters (default) | 36 characters |
| Size Reduction | 60% smaller | Baseline |
| Alphabet Size | 64 characters | 16 characters |
| URL-safe | Yes (by default) | Yes |
| Customizable | Yes (length & alphabet) | No |
| Generation Speed | 2x faster | Baseline |
How to Use NanoID Generator
Step 1: Configure Settings
Choose how many NanoIDs you need (1-10,000) and set the desired length (8-128 characters). The default length of 21 characters provides excellent collision resistance while keeping IDs compact. For most applications, the default settings are perfect.
Step 2: Customize Alphabet (Optional)
If you need a custom alphabet, enter it in the "Custom Alphabet" field. For example, use "0123456789" for numeric-only IDs, or "ABCDEFGHIJKLMNOPQRSTUVWXYZ" for uppercase letters only. Leave empty to use the default URL-safe alphabet.
Step 3: Generate NanoIDs
Click "Generate NanoIDs" to create your unique identifiers. Generation happens instantly in your browser using cryptographically secure random number generation. The collision probability is displayed based on your chosen length.
Step 4: Copy or Download
Click any NanoID to copy it to your clipboard, or use the "Download" button to save all generated IDs as a text file. The file contains one NanoID per line for easy importing.
Common Use Cases for NanoID
1. URL Shorteners
NanoID is perfect for URL shorteners because it creates compact, URL-safe identifiers. A 10-character NanoID provides enough uniqueness for billions of URLs while keeping the shortened URL as short as possible. Services like Vercel and many URL shorteners use NanoID for this purpose.
2. Database Primary Keys
Use NanoID as primary keys in databases where you want shorter IDs than UUID but still need global uniqueness. The compact size reduces storage requirements and improves index performance. NanoID works great with MongoDB, PostgreSQL, and other databases.
3. File and Document Names
NanoID generates perfect file names because they're short, unique, and don't contain special characters that cause problems in file systems. Use NanoID to name uploaded files, generated reports, or temporary files without worrying about conflicts.
4. Session IDs and Tokens
Generate secure session IDs and authentication tokens with NanoID. The cryptographically secure random generation ensures tokens are unpredictable, and the compact size reduces payload sizes in cookies and headers.
5. React Component Keys
When you need unique keys for React components and don't have natural IDs, NanoID provides a perfect solution. It's fast enough to generate during render without performance impact, and the IDs are stable across re-renders if generated once.
NanoID Examples
Example 1: JavaScript/Node.js
import { nanoid } from 'nanoid';
// Generate a NanoID
const id = nanoid();
console.log(id); // V1StGXR8_Z5jdHi6B-myT
// Custom length
const shortId = nanoid(10);
console.log(shortId); // IRFa-VaY2b
// Custom alphabet
import { customAlphabet } from 'nanoid';
const nanoid = customAlphabet('0123456789', 10);
const numericId = nanoid(); // 4193608123
Example 2: React Component
import { nanoid } from 'nanoid';
function TodoList() {
const [todos, setTodos] = useState([]);
const addTodo = (text) => {
setTodos([...todos, { id: nanoid(), text }]);
};
return (
<ul>
{todos.map(todo => (
<li key={todo.id}>{todo.text}</li>
))}
</ul>
);
}
Example 3: URL Shortener
import { customAlphabet } from 'nanoid';
// Use only URL-safe characters, 8 chars long
const nanoid = customAlphabet(
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',
8
);
const shortUrl = `https://short.link/${nanoid()}`;
console.log(shortUrl); // https://short.link/aB3dE5fG
Example 4: Database Schema
// MongoDB with Mongoose
const userSchema = new Schema({
_id: {
type: String,
default: () => nanoid()
},
email: String,
name: String
});
// PostgreSQL
CREATE TABLE users (
id VARCHAR(21) PRIMARY KEY DEFAULT nanoid(),
email VARCHAR(255) NOT NULL
);
Example 5: File Upload
import { nanoid } from 'nanoid';
import path from 'path';
function saveUploadedFile(file) {
const ext = path.extname(file.originalname);
const filename = `${nanoid()}${ext}`;
const filepath = `./uploads/${filename}`;
// Save file with unique name
fs.writeFileSync(filepath, file.buffer);
return filename;
}