shortid vs nanoid vs randomstring vs uuid
Generating Unique Identifiers in JavaScript Applications
shortidnanoidrandomstringuuidSimilar Packages:

Generating Unique Identifiers in JavaScript Applications

nanoid, randomstring, shortid, and uuid are all npm packages used to generate unique identifiers in JavaScript applications, but they differ significantly in design goals, collision resistance, output format, and suitability for modern frontend environments. uuid is the most mature and standards-compliant, producing universally unique identifiers (UUIDs) per RFC specifications. nanoid focuses on compact, URL-safe IDs with minimal size and high performance using cryptographically strong randomness. randomstring offers flexible string generation with extensive customization options but isn’t specifically designed for unique ID use cases. shortid was created to produce short, non-sequential IDs but has known limitations in uniqueness guarantees and is no longer maintained.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
shortid990,0705,71421.7 kB16a year agoMIT
nanoid026,89014.8 kB07 days agoMIT
randomstring052116.6 kB22 years agoMIT
uuid015,30565.7 kB2a month agoMIT

Generating Unique IDs in JavaScript: nanoid vs randomstring vs shortid vs uuid

When building modern web apps, you’ll often need to generate unique identifiers — for temporary DOM elements, client-side entity keys, cache entries, or sync tokens. But not all ID generators are created equal. Let’s break down how nanoid, randomstring, shortid, and uuid actually behave in real-world frontend scenarios.

🔢 What Kind of ID Do You Really Need?

Before comparing libraries, ask: What problem am I solving?

  • Globally unique across systems? → Use uuid.
  • Short, fast, client-only IDs? → Use nanoid.
  • Custom-formatted random text (not necessarily unique)? → Consider randomstring.
  • Legacy compatibility? → Avoid shortid; migrate away.

Each package makes different trade-offs between size, safety, standardization, and flexibility.

🧪 Collision Resistance: How Safe Is "Unique"?

uuid generates RFC-compliant identifiers. Version 4 (random-based) uses 122 bits of entropy — so the chance of collision is astronomically low, even at billions of IDs per second. This is why databases like PostgreSQL natively support UUIDs.

// uuid v4 example
import { v4 as uuidv4 } from 'uuid';
const id = uuidv4(); // '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d'

nanoid uses a larger alphabet (A-Za-z0-9_-) and defaults to 21 characters, giving ~126 bits of entropy — comparable to UUID v4 but in a shorter string. It leverages the browser’s crypto.getRandomValues() for true randomness, making it safe for client-side use.

// nanoid example
import { nanoid } from 'nanoid';
const id = nanoid(); // 'V1StGXR8_Z5jdHi6B-myT'

randomstring doesn’t guarantee uniqueness. It’s a general-purpose string generator. If you call it twice with the same settings, you might get duplicates — and there’s no built-in mechanism to prevent that.

// randomstring — not for unique IDs!
import randomstring from 'randomstring';
const str = randomstring.generate(10); // 'aB3xK9mQ2p' — could repeat

shortid uses only 7–14 characters with a small alphabet, resulting in very limited entropy. Worse, it relied on a shared internal counter that resets on app restart — causing predictable sequences and high collision risk in serverless or multi-tab environments. It is deprecated and should not be used in new code.

📏 Output Format and Size Matter

  • uuid: Always 36 chars (with hyphens). Hard to shorten safely.
  • nanoid: Default 21 chars, no special characters, URL-safe.
  • randomstring: Fully configurable — but defaults aren’t optimized for IDs.
  • shortid: ~7–10 chars, but unsafe.

If you’re embedding IDs in URLs or class names, nanoid’s compact, clean output wins. For database keys or API payloads where standards matter, uuid’s structure is an advantage.

🌐 Browser Compatibility and Security

All four work in browsers, but security differs:

  • nanoid and uuid both use cryptographically secure random sources in modern browsers (crypto.getRandomValues).
  • randomstring falls back to Math.random() unless you explicitly enable secure mode — which many developers forget.
  • shortid used insecure randomness in early versions and never updated its approach.

Never trust Math.random() for anything requiring uniqueness or unpredictability — it’s deterministic and easily guessable.

⚙️ Customization vs Simplicity

Need a 12-character alphanumeric ID without vowels (to avoid accidental words)? randomstring can do that:

randomstring.generate({
  length: 12,
  charset: 'abcdefghjkmnpqrstuvwxyz23456789'
});

But if you just need a safe, short ID with zero config, nanoid is simpler:

nanoid(12); // 'K7cL9pXqR2mN'

uuid offers versioned generation (e.g., time-based v1 or lexicographically sortable v7), useful for databases, but adds complexity if you don’t need it.

🛑 The Shortid Situation

shortid was popular around 2016–2018 for its brevity, but its author officially deprecated it in 2019, recommending nanoid as a replacement. Known issues include:

  • Collisions after ~16k IDs in a single process
  • Non-cryptographic randomness
  • No updates for modern JavaScript environments

If you see it in a codebase, treat it as technical debt.

✅ Practical Recommendations

Use CaseBest Choice
Client-side React keys, temp IDsnanoid
Database primary keys, API identifiersuuid (v4 or v7)
Test data, passwords, mock contentrandomstring
Any new project needing short IDsNot shortid — use nanoid

💡 Pro Tip: Avoid Reinventing the Wheel

Don’t roll your own ID generator using Date.now() + Math.random(). Even subtle bugs can cause hard-to-debug duplication issues in production. Stick to battle-tested libraries that understand entropy, randomness, and collision math.

In summary: Use nanoid for short client IDs, uuid for system-wide uniqueness, randomstring for non-unique random text, and never shortid in new code.

How to Choose: shortid vs nanoid vs randomstring vs uuid

  • shortid:

    Do not choose shortid for new projects. It is deprecated and no longer maintained, with documented issues around ID collisions under moderate load due to its limited entropy and reliance on process-specific counters. If you’re maintaining legacy code that uses it, plan a migration to nanoid or uuid.

  • nanoid:

    Choose nanoid when you need very short, URL-safe identifiers with strong uniqueness guarantees and minimal bundle impact. It’s ideal for client-side ID generation in SPAs, cache keys, or temporary DOM element IDs where size and speed matter. Its use of cryptographic randomness (via Web Crypto API in browsers) ensures low collision risk even at scale, and it avoids problematic characters like hyphens or underscores by default.

  • randomstring:

    Choose randomstring when your primary need is customizable random strings — not necessarily globally unique IDs. It shines in scenarios like password generation, test fixtures, or placeholder content where you control length, character sets, and patterns. However, avoid it for distributed ID generation since it lacks built-in collision resistance strategies and isn’t optimized for uniqueness.

  • uuid:

    Choose uuid when you need standards-compliant, universally unique identifiers — especially if interoperability with backend systems, databases, or external APIs is required. It supports multiple UUID versions (v1, v4, v7), with v4 being the most common for random IDs. While slightly larger than nanoid outputs (36 characters vs ~21), its predictability, widespread adoption, and robust collision resistance make it the safe default for most production systems.

README for shortid

shortid Build Status shortid

Amazingly short non-sequential url-friendly unique id generator.

shortid is deprecated, because the architecture is unsafe. we instead recommend Nano ID, which has the advantage of also being significantly faster than shortid

ShortId creates amazingly short non-sequential url-friendly unique ids. Perfect for url shorteners, MongoDB and Redis ids, and any other id users might see.

  • By default 7-14 url-friendly characters: A-Z, a-z, 0-9, _-
  • Supports cluster (automatically), custom seeds, custom alphabet.
  • Can generate any number of ids without duplicates, even millions per day.
  • Perfect for games, especially if you are concerned about cheating so you don't want an easily guessable id.
  • Apps can be restarted any number of times without any chance of repeating an id.
  • Popular replacement for Mongo ID/Mongoose ID.
  • Works in Node, io.js, and web browsers.
  • Includes Mocha tests.

ShortId does not generate cryptographically secure ids, so don't rely on it to make IDs which are impossible to guess.

Usage

const shortid = require('shortid');

console.log(shortid.generate());
// PPBqWA9

Mongoose Unique Id

_id: {
  'type': String,
  'default': shortid.generate
},

Browser Compatibility

The best way to use shortid in the browser is via browserify or webpack.

These tools will automatically only include the files necessary for browser compatibility.

All tests will run in the browser as well:

## build the bundle, then open Mocha in a browser to see the tests run.
$ grunt build open

Example

~/projects/shortid ❯ node examples/examples.js
eWRhpRV
23TplPdS
46Juzcyx
dBvJIh-H
2WEKaVNO
7oet_d9Z
dogPzIz8
nYrnfYEv
a4vhAoFG
hwX6aOr7

Real World Examples

shortId was created for Node Knockout 2011 winner for Most Fun Doodle Or Die. Millions of doodles have been saved with shortId filenames. Every log message gets a shortId to make it easy for us to look up later.

Here are some other projects that use shortId:

  • bevy - A simple server to manage multiple Node services.
  • capre - Cross-Server Data Replication.
  • cordova-build - an alternative to phonegap build that runs on your servers/agents.
  • couchdb-tools - A library of handy functions for use when working with CouchDB documents.
  • CleverStack/clever-email - E-mail system for CleverStack.
  • CloudTypes - JavaScript end2end implementation of the Cloud Types model for Eventual Consistency programming.
  • dnode-tarantula - an asynchronous rpc and event system for node.js based on dnode-protocol and TCP sockets.
  • mongoose-url-shortener - A simple URL Shortening library for NodeJS using Promises/A+ results.
  • mozilla/smokejumper - The Smoke Jumper project is an effort to bring dead simple, secure, P2P file sharing to Firefox.
  • shortness - Node based URL shortener that uses SQLite.
  • file-db - Document database that uses directories and files to store its data, supporting nested key-value objects in named collections.
  • resume-generator - Resume Generator.
  • riffmint - Collaboration in musical space.
  • rap1ds/dippa - Dippa Editor – A web-based LaTeX editor

API

var shortid = require('shortid');

shortid.generate()

Returns string non-sequential unique id.

Example

users.insert({
  _id: shortid.generate(),
  name: '...',
  email: '...'
});

shortid.characters(string)

Default: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_'

Returns new alphabet as a string

Recommendation: If you don't like _ or -, you can to set new characters to use.

Optional

Change the characters used.

You must provide a string of all 64 unique characters. Order is not important.

The default characters provided were selected because they are url safe.

Example

// use $ and @ instead of - and _
shortid.characters('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$@');
// any 64 unicode characters work, but I wouldn't recommend this.
shortid.characters('ⒶⒷⒸⒹⒺⒻⒼⒽⒾⒿⓀⓁⓂⓃⓄⓅⓆⓇⓈⓉⓊⓋⓌⓍⓎⓏⓐⓑⓒⓓⓔⓕⓖⓗⓘⓙⓚⓛⓜⓝⓞⓟⓠⓡⓢⓣⓤⓥⓦⓧⓨⓩ①②③④⑤⑥⑦⑧⑨⑩⑪⑫');

shortid.isValid(id)

Returns boolean

Check to see if an id is a valid shortid. Note: This only means the id could have been generated by shortid, it doesn't guarantee it.

Example

shortid.isValid('41XTDbE');
// true
shortid.isValid('i have spaces');
// false

shortid.worker(integer)

Default: process.env.NODE_UNIQUE_ID || 0

Recommendation: You typically won't want to change this.

Optional

If you are running multiple server processes then you should make sure every one has a unique worker id. Should be an integer between 0 and 16. If you do not do this there is very little chance of two servers generating the same id, but it is theoretically possible if both are generated in the exact same second and are generating the same number of ids that second and a half-dozen random numbers are all exactly the same.

Example

shortid.worker(1);

shortid.seed(integer)

Default: 1

Recommendation: You typically won't want to change this.

Optional

Choose a unique value that will seed the random number generator so users won't be able to figure out the pattern of the unique ids. Call it just once in your application before using shortId and always use the same value in your application.

Most developers won't need to use this, it's mainly for testing ShortId.

If you are worried about users somehow decrypting the id then use it as a secret value for increased encryption.

Example

shortid.seed(1000);

About the Author

Hi! Thanks for checking out this project! My name is Dylan Greene. When not overwhelmed with my two young kids I enjoy contributing to the open source community. I'm also a tech lead at Opower. @dylang @dylang

Here's some of my other Node projects:

NameDescriptionnpm Downloads
npm‑checkCheck for outdated, incorrect, and unused dependencies.npm-check
grunt‑notifyAutomatic desktop notifications for Grunt errors and warnings. Supports OS X, Windows, Linux.grunt-notify
space‑hogsDiscover surprisingly large directories from the command line.space-hogs
rssRSS feed generator. Add RSS feeds to any project. Supports enclosures and GeoRSS.rss
grunt‑promptInteractive prompt for your Grunt config using console checkboxes, text input with filtering, password fields.grunt-prompt
xmlFast and simple xml generator. Supports attributes, CDATA, etc. Includes tests and examples.xml
changelogCommand line tool (and Node module) that generates a changelog in color output, markdown, or json for modules in npmjs.org's registry as well as any public github.com repo.changelog
grunt‑attentionDisplay attention-grabbing messages in the terminalgrunt-attention
observatoryBeautiful UI for showing tasks running on the command line.observatory
anthologyModule information and stats for any @npmjs useranthology
grunt‑catEcho a file to the terminal. Works with text, figlets, ascii art, and full-color ansi.grunt-cat

This list was generated using anthology.

License

Copyright (c) 2016 Dylan Greene, contributors.

Released under the MIT license.

Screenshots are CC BY-SA (Attribution-ShareAlike).