• Stars
    star
    5,736
  • Rank 7,102 (Top 0.2 %)
  • Language
    JavaScript
  • License
    Other
  • Created almost 13 years ago
  • Updated about 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Short id generator. Url-friendly. Non-predictable. Cluster-compatible.

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:

Name Description npm Downloads
npm‑check Check for outdated, incorrect, and unused dependencies. npm-check
grunt‑notify Automatic desktop notifications for Grunt errors and warnings. Supports OS X, Windows, Linux. grunt-notify
space‑hogs Discover surprisingly large directories from the command line. space-hogs
rss RSS feed generator. Add RSS feeds to any project. Supports enclosures and GeoRSS. rss
grunt‑prompt Interactive prompt for your Grunt config using console checkboxes, text input with filtering, password fields. grunt-prompt
xml Fast and simple xml generator. Supports attributes, CDATA, etc. Includes tests and examples. xml
changelog Command 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‑attention Display attention-grabbing messages in the terminal grunt-attention
observatory Beautiful UI for showing tasks running on the command line. observatory
anthology Module information and stats for any @npmjs user anthology
grunt‑cat Echo 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).

More Repositories

1

npm-check

Check for outdated, incorrect, and unused dependencies.
JavaScript
6,553
star
2

node-rss

RSS feed generator for Node.
JavaScript
995
star
3

grunt-notify

Automatic Notifications when Grunt tasks fail.
JavaScript
921
star
4

grunt-prompt

Add interactive UI to your Gruntfile such as lists, checkboxes, text input with filtering, and password fields, all on the command line.
JavaScript
368
star
5

observatory

Beautiful UI for showing tasks running on the command line.
JavaScript
276
star
6

node-xml

Fast and simple Javascript-based XML generator/builder for Node projects.
JavaScript
274
star
7

changelog

Finally see what's changed when you do npm update. Changelog generates a changelog for npm modules and github repos.
JavaScript
239
star
8

space-hogs

Discover surprisingly large directories from the command line.
JavaScript
161
star
9

opowerjobs

Node.js site using Express and Connect.
JavaScript
61
star
10

logging

Lightweight informative modern console logging.
JavaScript
54
star
11

anthology

List of modules for any npm user, plus number of downloads and github stars.
JavaScript
46
star
12

captionbot

Get captions for image using Microsoft's CaptionBot
JavaScript
41
star
13

grunt-attention

Display attention-grabbing messages in the terminal.
JavaScript
26
star
14

jira-improved

Improves the Jira Agile board by showing the Epic name in the cards and hiding the Done column if you use a quick filter to hide tickets in that column.
JavaScript
24
star
15

node-atom

DEPRECATED - NOT MAINTAINED
JavaScript
20
star
16

what-dog

Get the breed of a dog from an image using Microsoft's what-dog
JavaScript
15
star
17

grunt-cat

Echo a file to the terminal. Works with text, figlets, ascii art, and full-color ansi.
JavaScript
14
star
18

random-puppy

Get a random puppy image url.
JavaScript
13
star
19

jobvite

DEPRECATED ----- Jobvite API for Node
JavaScript
12
star
20

source-map-diff

Compare source maps with cli and web output
TypeScript
7
star
21

flowdock-refined

DEPRECATED - Flowdock desktop app custom UI
CSS
5
star
22

...

really, this is a valid project name?
2
star
23

dotfiles

Vim Script
2
star
24

lean

Simple in-memory data store to lean on. Helpful when you don't need a couch.
JavaScript
2
star
25

jquery-tooltips

Easy to use image-free HTML5 tooltips for jQuery 1.5.2+.
JavaScript
2
star
26

grunt-templates-dylang

Templates for grunt-readme that dylang will be using across multiple projects.
JavaScript
1
star
27

dotconfig

My custom terminal colors, bash-it prompt, intellij and webstorm settings, etc
Shell
1
star
28

dylang.github.com

Everything you need to know about me.
1
star