I would like to generate a short unique alphanumeric value to be used as confirmation codes for online purchases. I've looking into https://github.com/broofa/node-uuid but their uuids are too long and I want to have them be around 8 characters long. What is the best way I can achieve this?
-
4Unique and short do not go hand-in-hand unless you can guarantee that they have a single origin, or have some interlocking method so that two servers will not generate the same strings. – Brad Jun 11 '12 at 18:58
-
1If you use a hash function you could try to determine the shortest currently possible substring of the hash result, similar how git abbreviate the commit hashes. – TheHippo Jun 11 '12 at 19:06
6 Answers
10/23/15: See the hashids answer below, as well!
You can borrow from the URL shortener model and do something like this:
(100000000000).toString(36);
// produces 19xtf1ts
(200000000000).toString(36);
// produces 2jvmu3nk
Just increment the number to keep it unique:
function(uniqueIndex) {
return uniqueIndex.toString(36);
}
Note that this is only really useful for "single instance" services that don't mind a certain amount of predictability in the way this is ordered (via basic increment). If you need a truly unique value across a number of application / DB instances, you should really consider a more full featured option per some of the comments.

- 3,063
- 23
- 32
-
2Thanks for the tip. I ended up using something similar to what you provided: var now = new Date(); Math.floor(Math.random() * 10) + parseInt(now.getTime()).toString(36).toUpperCase() – teggy Jun 13 '12 at 21:51
-
1What does the `parseInt` add? Wouldn't `(100000000000).toString(36)` work just as well? – JohnnyHK Sep 28 '12 at 12:44
-
-
7@teggy, what's the point to use random? `(+new Date()).toString(36)` should give you unique id. – pronebird Mar 31 '13 at 20:13
-
@Andy the only reason i added the random part was so i can have the string start with a number, which i thought looked better for an online purchase confirmation code – teggy Apr 22 '13 at 22:01
-
1alternatively: `Array.apply(0, Array(n)).reduce(function(p){return p + (Math.random() * 1e18).toString(36)}, '')` will generate an around (12 * `n`) length string – marcelduran Jul 30 '13 at 23:04
-
(+new Date()).toString(36) + (Math.random().toString().replace('.', '')); – Sparky Oct 25 '13 at 09:33
-
6The only flaw with this approach is it doesn't guarantee uniqueness in parallel environments. Two machines or processes could generate a code at the same time and you can have conflicts. – Owen Allen Feb 07 '14 at 16:41
-
Here is a simpler unique ID Math.random().toString(36).replace('0.', ''); – Ash Blue Apr 22 '14 at 02:48
-
`Math.round(Math.random() * 100000000 + 1000000000).toString(36).toUpperCase()` returns `'GJF4FC'`-like results. Great! – Costin Feb 28 '18 at 10:34
A little late on this one but it seems like hashids would work pretty well for this scenario.
https://github.com/ivanakimov/hashids.node.js
hashids (Hash ID's) creates short, unique, decryptable hashes from unsigned integers
var Hashids = require('hashids'),
hashids = new Hashids('this is my salt');
var hash = hashids.encrypt(12345);
// hash is now 'ryBo'
var numbers = hashids.decrypt('ryBo');
// numbers is now [ 12345 ]
If you want to target ~ 8 characters you could do, the following that calls for a minimum of 8 chars.
hashids = new Hashids("this is my salt", 8);
then this:
hash = hashids.encrypt(1);
// hash is now 'b9iLXiAa'
The accepted answer would be predictable/guessable, this solution should be unique and unpredictable.

- 2,501
- 6
- 26
- 29
-
Updates on hashids as of 1.0.0. Several public functions are renamed to be more appropriate: **Function encrypt() changed to encode()**, **Function decrypt() changed to decode()**, **Function encryptHex() changed to encodeHex()**, **Function decryptHex() changed to decodeHex()** – Arman Ortega Jan 28 '15 at 09:42
-
1
-
encrypting & decrypting are probably expensive operations for a simple ID generation – Shalom Sam Jan 13 '18 at 07:43
-
Install shortId module (https://www.npmjs.com/package/shortid). By default, shortid generates 7-14 url-friendly characters: A-Z, a-z, 0-9, _- but you can replace - and _ with some other characters if you like. Now you need to somehow stick this shortId to your objects when they're being saved in the database. Best way is to stick them in Schema like this:
var shortId = require('shortid');
var PurchaseConfirmationSchema = mongoose.Schema({
/* _id will be added automatically by mongoose */
shortId: {type: String, unique: true, default: shortId.generate}, /* WE SHOULD ADD THIS */
name: {type: String},
address: {type: String}
});
I already answered similiar question to myself over here:
-
1Hi, is shortId will give unique string even after server restarts? – Nalla Srinivas Sep 07 '15 at 11:15
-
2But it requires a dictionary of exactly 64 characters, so it's not going to be alphanumeric even if you replace - and _. – James M Sep 19 '17 at 14:26
For this purpose I wrote a module that can do that and ever more. Look at its page: id-shorter

- 2,703
- 1
- 16
- 17
IF each online purchase associated to Unique URL , you can use the backend of simple-short package,which don't require database connection, nor web services :
var shorten=require('simple-short');
shorten.conf({length:8}); // Default is 4.
code1=shorten('http://store.com/purchase1');
code2=shorten('http://store.com/purchase2');
//.. so on

- 87,526
- 38
- 249
- 254
based on this https://www.npmjs.com/package/randomstring
var randomstring = require("randomstring");
randomstring.generate();
// >> "XwPp9xazJ0ku5CZnlmgAx2Dld8SHkAeT"
randomstring.generate(7);
// >> "xqm5wXX"
randomstring.generate({
length: 12,
charset: 'alphabetic'
});
// >> "AqoTIzKurxJi"
randomstring.generate({
charset: 'abc'
});
// >> "accbaabbbbcccbccccaacacbbcbbcbbc"
you can do this
randomstring.generate({
length: 8,
charset: 'alphabetic'
});