Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

short-unique-id

jeanlescure2.5mApache-2.05.2.0TypeScript support: included

Generate random or sequential UUID of any length

short, random, uid, uuid, guid, node, unique id, generator, tiny

readme

Short Unique ID (UUID) Generating Library

Tests Try short-unique-id on RunKit NPM Downloads JsDelivr Hits

15 Contributors


Tiny (6.7kB minified) no-dependency library for generating random or sequential UUID of any length with exceptionally minuscule probabilies of duplicate IDs.

const uid = new ShortUniqueId({ length: 10 });
uid.rnd(); // p0ZoB1FwH6
uid.rnd(); // mSjGCTfn8w
uid.rnd(); // yt4Xx5nHMB
// ...

// or

const { randomUUID } = new ShortUniqueId({ length: 10 });
randomUUID(); // e8Civ0HoDy
randomUUID(); // iPjiGoHXAK
randomUUID(); // n528gSMwTN
// ...

For example, using the default dictionary of numbers and letters (lower and upper case):

  0,1,2,3,4,5,6,7,8,9,
  a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,
  A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z
  • if you generate a unique ID of 16 characters (half of the standard UUID of 32 characters)
  • generating 100 unique IDs per second

It would take ~10 thousand years to have a 1% probability of at least one collision!

To put this into perspective:

  • 73 years is the (global) average life expectancy of a human being
  • 120 years ago no human ever had set foot on either of the Earth's poles
  • 480 years ago Nicolaus Copernicus was still working on his theory of the Earth revolving around the Sun
  • 1000 years ago there was no such thing as government-issued paper money (and wouldn't be for about a century)
  • 5000 years ago the global population of humans was under 50 million (right now Mexico has a population of 127 million)

You can calculate duplicate/collision probabilities using the included functions:

NOTE: 👆 On these links you will also find explanations for the math used within the functions.


Open source notice

This project is part of the Open Collective project Simply Hexagonal and is open to updates by its users, we ensure that PRs are relevant to the community. In other words, if you find a bug or want a new feature, please help us by becoming one of the contributors ✌️ ! See the contributing section.

Like this module? ❤

Please consider:

📣 v5 Notice

In order to improve security compliance we have removed the ability to use a ShortUniqueId as a function, i.e. const uid = new ShortUniqueId(); uid(); is no longer supported.

If you plan to upgrade to v5 make sure to refactor uid(); to uid.rnd(); in your code beforehand.

For more information regarding this decision you can view issue #53.

Features

Ability to generate UUIDs that contain a timestamp which can be extracted:

// js/ts

const uid = new ShortUniqueId();

const uidWithTimestamp = uid.stamp(32);
console.log(uidWithTimestamp);
// GDa608f973aRCHLXQYPTbKDbjDeVsSb3

const recoveredTimestamp = uid.parseStamp(uidWithTimestamp);
console.log(recoveredTimestamp);
// 2021-05-03T06:24:58.000Z
# cli

$ suid -s -l 42

  lW611f30a2ky4276g3l8N7nBHI5AQ5rCiwYzU47HP2

$ suid -p lW611f30a2ky4276g3l8N7nBHI5AQ5rCiwYzU47HP2

  2021-08-20T04:33:38.000Z

Default dictionaries (generated on the spot to reduce memory footprint and avoid dictionary injection vulnerabilities):

  • number
  • alpha
  • alpha_lower
  • alpha_upper
  • alphanum (default when no dictionary is provided to new ShortUniqueId())
  • alphanum_lower
  • alphanum_upper
  • hex
// instantiate using one of the default dictionary strings
const uid = new ShortUniqueId({
  dictionary: 'hex',
});

console.log(uid.dict.join());
// 0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f

// or change the dictionary after instantiation
uid.setDictionary('alpha_upper');

console.log(uid.dict.join());
// A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z

Ability to use custom formatting

Where $r is random UUID, $s is sequential UUID, and $t is timestamp UUID:

const timestamp = new Date('4-01-29T03:21:21.000Z');
const result = uid.formattedUUID('Time: $t0 ID: $s2-$r4', timestamp); // timestamp is optional

console.log(result);
// Time: 63d5e631 ID: 0b-aaab

Ability to validate UUIDs against the instance dictionary or a provided dictionary

Example of using .validate() method:

// Instantiate using one of the default dictionary strings
const uid = new ShortUniqueId({
  dictionary: 'hex',
});

const uuid = uid.stamp(32); // Generate a UUID

// Validate the generated UUID against the instance dictionary
const isValid = uid.validate(uuid);

console.log(`Is the UUID valid? ${isValid}`);

// ---

// Validate the generated UUID against the provided dictionary
const customDictionary = ['a', 'b', /* ... */];
const isValid = uid.validate(uuid, customDictionary);

console.log(`Is the UUID valid? ${isValid}`);

Use in CLI

$ npm install --global short-unique-id

$ suid -h

# Usage:
#   node short-unique-id [OPTION]
# 
# Options:
#   -l, --length=ARG         character length of the uid to generate.
#   -s, --stamp              include timestamp in uid (must be used with --length (-l) of 10 or more).
#   -t, --timestamp=ARG      custom timestamp to parse (must be used along with -s, --stamp, -f, or --format).
#   -f, --format=ARG         string representing custom format to generate id with.
#   -p, --parse=ARG          extract timestamp from stamped uid (ARG).
#   -d, --dictionaryJson=ARG json file with dictionary array.
#   -h, --help               display this help

Use as module

Add to your project:

// ES6 / TypeScript Import
import ShortUniqueId from 'short-unique-id';

// Node.js require
const ShortUniqueId = require('short-unique-id');

// Deno (web module) Import
import ShortUniqueId from 'https://esm.sh/short-unique-id';

Instantiate and use:

//Instantiate
const uid = new ShortUniqueId();

// Random UUID
console.log(uid.rnd());

// Sequential UUID
console.log(uid.seq());

alternatively using destructuring assignment:

// Instantiate and destructure (long method name recommended for code readability)
const { randomUUID, sequentialUUID } = new ShortUniqueId();

// Random UUID
console.log(randomUUID());

// Sequential UUID
console.log(sequentialUUID());

NOTE: we made sure to use bind() on all ShortUniqueId methods to ensure that any options passed when creating the instance will be respected by the destructured methods.

Use in browser

<!-- Add source (minified 4.6kB) -->
<script src="https://cdn.jsdelivr.net/npm/short-unique-id@latest/dist/short-unique-id.min.js"></script>

<!-- Usage -->
<script>
  // Instantiate
  var uid = new ShortUniqueId();

  // Random UUID
  document.write(uid.rnd());

  // Sequential UUID
  document.write(uid.seq());
</script>

Options

Options can be passed when instantiating uid:

const options = { ... };

const uid = new ShortUniqueId(options);

For more information take a look at the docs.

Available for

Documentation with Online Short UUID Generator

You can find the docs and online generator at:

https://shortunique.id

What is the probability of generating the same id again?

This largely depends on the given dictionary and the selected UUID length.

Out of the box this library provides a shuffled dictionary of digits from 0 to 9, as well as the alphabet from a to z both in UPPER and lower case, with a default UUID length of 6. That gives you a total of 56,800,235,584 possible UUIDs.

So, given the previous values, the probability of generating a duplicate in 1,000,000 rounds is ~0.00000002, or about 1 in 50,000,000.

If you change the dictionary and/or the UUID length then we have provided the function collisionProbability() function to calculate the probability of hitting a duplicate in a given number of rounds (a collision) and the function uniqueness() which provides a score (from 0 to 1) to rate the "quality" of the combination of given dictionary and UUID length (the closer to 1, higher the uniqueness and thus better the quality).

To find out more about the math behind these functions please refer to the API Reference.

Acknowledgement and platform support

This repo and npm package started as a straight up manual transpilation to ES6 of the short-uid npm package by Ankit Kuwadekar.

image depicting over 200000 weekly npm downloads image depicting over 16000000 weekly cdn hits

Since this package is now reporting 200k+ npm weekly downloads and 16M+ weekly cdn hits, we've gone ahead and re-written the whole of it in TypeScript and made sure to package dist modules compatible with Deno, Node.js and all major Browsers.

Sponsors

Development

Clone this repo:

# SSH
git clone git@github.com:jeanlescure/short-unique-id.git

# HTTPS
git clone https://github.com/jeanlescure/short-unique-id.git

Tests run using:

pnpm test

Build

In order to publish the latest changes you must build the distribution files:

pnpm build

Then commit all changes and run the release script:

pnpm release

Contributing

Yes, thank you! This plugin is community-driven, most of its features are from different authors. Please update the docs and tests and add your name to the package.json file.

Contributors ✨

Thanks goes to these wonderful people (emoji key):

💻
🚧 💻 📖 ⚠️
💻
💻
💻 👀
💻
💻
🤔
🛡️
💻
💻
📖
🤔
🤔
🤔

License

Copyright (c) 2018-2024 Short Unique ID Contributors.
Licensed under the Apache License 2.0.

changelog

Changelog

All notable changes to this project will be documented in this file. Dates are displayed in UTC.

Generated by auto-changelog.

v5.2.0

  • chore: refactor constructable fix for automated release faac3dc
  • docs: fix broken links and images e1433f9
  • chore: build dist and docs for release ff28c8e

v5.1.1

29 April 2024

  • chore: build dist and docs for release 4c9fb32
  • docs: update docs 7f91955
  • docs: update version in docs 0db7cd0

v5.1.0

29 April 2024

  • chore(deps-dev): bump ip from 1.1.8 to 1.1.9 #60
  • chore: merge conflicts 0b41ad6
  • chore: build dist and docs for release 2d08da0
  • Release 5.0.4 92ecf98

v5.0.4

29 April 2024

  • chore: add specs to address #59 import concerns 3f8fc65
  • Release 5.0.4 5a05d4e
  • chore: build dist and docs for release f103ec7

v5.0.3

23 September 2023

  • Release 5.0.3 96422ba
  • docs: add back the live UUID generator 4bdb9ff
  • chore: build dist and docs for release 3876a57

v5.0.2

4 September 2023

  • docs: update docs for v5 5fed48e
  • chore: build v5 release 6acc4e7
  • chore: build dist and docs for release 7df37ae

v4.4.4

22 September 2021

  • Release 4.4.4 279a026
  • chore: build dist and docs for release 26b8185
  • chore: add back runkit example 227993b

v4.4.3

22 September 2021

  • chore: replace yarn with pnpm 8de535a
  • Release 4.4.3 256bc45
  • chore: build dist and docs for release 592d432

v4.4.2

10 September 2021

  • fix: browser error exports is not defined fixes #50 #50
  • chore: build dist and docs for release e2f0ae9
  • Release 4.4.2 984437b

v4.4.0

6 September 2021

  • chore: implement release-it for version management 48228d7
  • wip: remove standard-version as first step to replace it with release-it 9ab8483
  • Release 4.4.0 097cf23

v4.3.8

29 August 2021

  • chore: build dist and docs for release 7429c8f
  • docs(contributors): add new contributors e53054b
  • chore(release): 4.3.8 3659bdf

4.3.6

29 August 2021

v4.3.6

29 August 2021

  • chore(package): map TS types explicitly #48
  • chore: build dist and docs for release fd98f01
  • chore: build dist and docs for release a74c21e
  • docs(contributors): add new contributors b271c23

v4.3.5

29 August 2021

  • chore: build dist and docs for release c698979
  • chore(release): 4.3.5 31d5580
  • fix: types being inferred in certain situations rather than using .d.ts file 94738e5

v4.3.4

20 August 2021

  • chore(deps): bump path-parse from 1.0.6 to 1.0.7 #44
  • chore: merge remote changes 7c29722
  • chore: build dist and docs for release 06fad68
  • chore: replaced rollup with esbuild 645e338

v4.3.3

6 May 2021

  • chore: build dist and docs for release d7ee492
  • chore: remove unnecessary files from package e9570d2
  • chore(release): 4.3.3 fa44a31

v4.3.2

4 May 2021

  • fix: default is not a constructor when using allowSyntheticDefaultImports 61a9ad7
  • chore: build dist and docs for release 0bb0064
  • chore(release): 4.3.2 e817a73

v4.3.1

4 May 2021

  • docs: update links and weekly numbers 4e298a9
  • chore: build dist and docs for release 397640b
  • chore(release): 4.3.1 6126924

v4.3.0

4 May 2021

  • feat: add immutable default dictionaries 3dd1026
  • chore: make sure minified dist file is as small as possible ca6d646
  • chore: build dist and docs for release ed1bca0

v4.2.1

3 May 2021

  • chore: build dist and docs for release c6f2f2a
  • fix: error in docs when scrolling 5329c26
  • chore(release): 4.2.1 f36f00a

v4.2.0

3 May 2021

  • chore: build dist and docs for release 712bc04
  • chore(release): 4.2.0 f89bde6
  • chore: point test to development code bcb263f

v4.1.3

3 May 2021

  • chore: make sure dist version matches release 012c444
  • chore: build dist and docs for release 50207c7
  • chore(release): 4.1.3 0c089dc

v4.1.2

3 May 2021

  • chore: make sure dist version matches release aa77bf9
  • chore(release): 4.1.2 9a2325f
  • chore: make sure dist version matches release ddbe45a

v4.1.0

3 May 2021

v4.0.2

3 May 2021

v4.0.1

3 May 2021

v4.0.0

3 May 2021

  • Refactor skip shuffle #5
  • Refactor sequential UUID #4
  • Uniqueness #3
  • Add length option #2
  • refactor instance to allow uid() instead of uid.randomUUID() #1
  • feat: complete refactor and added stamp/parseStamp methods 2c09d04
  • implement functionality necessary for collision and uniqueness calculation 0b7a4ca
  • initial commit 9d2c55d

3.0.4

19 July 2020

v3.0.4

19 July 2020

  • Bump lodash from 4.17.15 to 4.17.19 #33
  • adjust tsconfig and bump version 75e0fae
  • remove conflicting publish config 11f7b90
  • add publish config 7832dfa

v3.0.3

1 June 2020

  • update homepage in package.json f206452

v3.0.2

21 May 2020

  • Fix typings #30
  • fix all typings, docs, and npm pack issues 29c8b55
  • version bump and feature creep a release prep script 3d48ace
  • update short_uuid to latest commit 194b238

v3.0.1

20 May 2020

  • fix typings issue, update docs, and bump version 65693b6

v3.0.0

14 May 2020

  • Release v3.0.0 #27
  • docs: add ekelvin as a contributor #25
  • docs: add angelnath26 as a contributor #24
  • docs: add EmerLM as a contributor #23
  • docs: add DiLescure as a contributor #22
  • docs: add serendipious as a contributor #21
  • docs: add neversun as a contributor #18
  • docs: add jeffturcotte as a contributor #17
  • docs: add jeanlescure as a contributor #16
  • release v3 1bb895d
  • promote v3 docs up to master to test on gh pages 2c3e64c
  • updated docs b315255

v3.0.0-rc2

11 May 2020

  • fix online generator link and title #10
  • Fix unexpected token error due to class property usage #9
  • Fix ReferenceError: window is not defined #7
  • full refactor using neutrino #5
  • Removed uncommon syntax for post-processors (uglifyjs-webpack-plugin) #2
  • rc2 refactors out version json import, fixes #26 #26
  • implemented lib and dist build scripts, closes #13 #13
  • starting branch for v3, closes #12 #12
  • fix #8 Unexpected token error due to class property usage #8
  • fix #6 reference error window undefined in node require #6
  • updated readme and npm meta 5f8f7cf
  • add runkit test and example c00c1e9
  • upgrade docs to typedoc 3793828

v3.0.0-rc1

4 May 2020

  • Refactor skip shuffle #5
  • Refactor sequential UUID #4
  • Uniqueness #3
  • Add length option #2
  • refactor instance to allow uid() instead of uid.randomUUID() #1
  • documentation and version updates 63f3251
  • removed unnecessary type definitions file bb2156c
  • merge master and finish shuffle refactor d6313f2

v3.0.0-alpha

3 May 2020

  • implemented lib and dist build scripts, closes #13 #13
  • starting branch for v3, closes #12 #12
  • upgrade docs to typedoc 3793828
  • implemented collision probability, uniqueness, and refactored seq f4f8034
  • complete deno refactor including test and lint 0a2a7eb

2.0.7

14 April 2020

  • fix online generator link and title #10
  • dist updated 42955df

v2.0.7

14 April 2020

2.0.6

12 March 2020

v2.0.6

12 March 2020

  • Fix unexpected token error due to class property usage #9
  • fix #8 Unexpected token error due to class property usage #8
  • dist updated 12272d0
  • change lib's browser route in README to use unpkg 9709ce3
  • correct README test suite reference 3b2e3b1

2.0.5

11 March 2020

v2.0.5

11 March 2020

  • Fix ReferenceError: window is not defined #7
  • fix #6 reference error window undefined in node require #6
  • updated readme and npm meta 5f8f7cf
  • add runkit test and example c00c1e9
  • dist updated 477dd20

2.0.4

9 March 2020

v2.0.4

9 March 2020

2.0.1

3 March 2020

  • add online generator link to README b09ea8c
  • fix README and online generator b8852da

2.0.0

3 March 2020

  • full refactor using neutrino #5
  • Removed uncommon syntax for post-processors (uglifyjs-webpack-plugin) #2
  • Did it all in one go. Gosh darn it! :wink: c74d434
  • Massive lint refactor. 7bc7354
  • Removed uncommon syntax for post-processors a0a6545