- Notifications
You must be signed in to change notification settings - Fork204
A small JavaScript library to generate YouTube-like ids from numbers.
License
niieani/hashids.js
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Hashids is small JavaScript library to generate YouTube-like ids from numbers. Use it when you don't want to expose your database ids to the user:http://hashids.org/javascript
Install Hashids via:
yarn add hashids
(or just directly use the code atdist/hashids.js)
importHashidsfrom'hashids'consthashids=newHashids()console.log(hashids.encode(1))
constHashids=require('hashids/cjs')consthashids=newHashids()console.log(hashids.encode(1))
Note: When using Node that supportsconditional exports,require('hashids') (version >=13) will also work.
<scripttype="text/javascript"src="hashids.min.js"></script><scripttype="text/javascript">varhashids=newHashids();console.log(hashids.encode(1));</script>
import orrequire, based on the environment (see above). If you want to use the CommonJS module syntax (require), you'll need to install the Node.js types from theDefinitelyTyped repository.
npm install @types/nodeIf you want to use the ESM syntax (import Hashids from 'hashids'), you will need to include the following options in yourtsconfig.json.
{"allowSyntheticDefaultImports":true,"esModuleInterop":true}The above is not required if you import the CommonJS version directly:import Hashids from 'hashids/cjs'.
If you get errors stating:Cannot find name 'BigInt', add"esnext.bigint" or"esnext" to yourtsconfig.json file, under"lib":
{"compilerOptions": {..."lib": ["esnext.bigint",... ] }}Note that your environment doesn't actually have to supportBigInt for hashids to function.
consthashids=newHashids()constid=hashids.encode(1,2,3)// o2fXhVconstnumbers=hashids.decode(id)// [1, 2, 3]
A few more ways to pass toencode():
consthashids=newHashids()console.log(hashids.encode(1,2,3))// o2fXhVconsole.log(hashids.encode([1,2,3]))// o2fXhV// strings containing integers are coerced to numbers:console.log(hashids.encode('1','2','3'))// o2fXhVconsole.log(hashids.encode(['1','2','3']))// o2fXhV// BigInt support:console.log(hashids.encode([1n,2n,3n]))// o2fXhV// Hex notation BigInt:console.log(hashids.encode([0x1n,0x2n,0x3n]))// o2fXhV
Make your ids unique:
Pass a "salt" to make your ids unique (e.g. a project name):
varhashids=newHashids('My Project')console.log(hashids.encode(1,2,3))// Z4UrtWvarhashids=newHashids('My Other Project')console.log(hashids.encode(1,2,3))// gPUasb
Use padding to make your ids longer:
Note that ids are only padded to fitat least a certain length. It doesn't mean that your ids will beexactly that length.
consthashids=newHashids()// no paddingconsole.log(hashids.encode(1))// jRconsthashids=newHashids('',10)// pad to length 10console.log(hashids.encode(1))// VolejRejNm
Pass a custom alphabet:
consthashids=newHashids('',0,'abcdefghijklmnopqrstuvwxyz')// all lowercaseconsole.log(hashids.encode(1,2,3))// mdfphx
Default alphabet isabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.
Since v2.0 you can even use emojis as the alphabet.
Encode hex instead of numbers:
Useful if you want to encode numbers likeMongo's ObjectIds.
Note that there isno limit on how large of a hex number you can pass.
varhashids=newHashids()varid=hashids.encodeHex('507f1f77bcf86cd799439011')// y42LW46J9luq3Xq9XMlyvarhex=hashids.decodeHex(id)// 507f1f77bcf86cd799439011
Please note that this is not the equivalent of:
consthashids=newHashids()constid=Hashids.encode(BigInt('0x507f1f77bcf86cd799439011'))// y8qpJL3ZgzJ8lWk4GEVconsthex=Hashids.decode(id)[0].toString(16)// 507f1f77bcf86cd799439011
The difference between the two is that the built-inencodeHex willalways result in the same length, even if it contained leading zeros.
For examplehashids.encodeHex('00000000') would encode toqExOgK7 and decode back to'00000000' (length information is preserved).
When decoding, output is always an array of numbers (even if you encode only one number):
consthashids=newHashids()constid=hashids.encode(1)console.log(hashids.decode(id))// [1]
Encoding negative numbers is not supported.
If you pass bogus input to
encode(), an empty string will be returned:consthashids=newHashids()constid=hashids.encode('123a')console.log(id==='')// true
Do not use this library as a security tool and do not encode sensitive data. This isnot an encryption library.
The primary purpose of Hashids is to obfuscate ids. It's not meant or tested to be used as a security or compression tool. Having said that, this algorithm does try to make these ids random and unpredictable:
No repeating patterns showing there are 3 identical numbers in the id:
consthashids=newHashids()console.log(hashids.encode(5,5,5))// A6t1tQ
Same with incremented numbers:
consthashids=newHashids()console.log(hashids.encode(1,2,3,4,5,6,7,8,9,10))// wpfLh9iwsqt0uyCEFjHMconsole.log(hashids.encode(1))// jRconsole.log(hashids.encode(2))// k5console.log(hashids.encode(3))// l5console.log(hashids.encode(4))// mOconsole.log(hashids.encode(5))// nR
This code was written with the intent of placing created ids in visible places, like the URL. Therefore, by default the algorithm tries to avoid generating most common English curse words by generating ids that never have the following letters next to each other:
c, f, h, i, s, t, uYou may customize the chars that shouldn't be placed next to each other by providing a 4th argument to the Hashids constructor:
// first 4 arguments will fallback to defaults (empty salt, no minimum length, default alphabet)consthashids=newHashids(undefined,undefined,undefined,'zyxZYX')
If your environment supportsBigInt, you can use the standard APIto encode and decode them the same way as ordinary numbers.
Trying to decode aBigInt-encoded hashid on an unsupported environment will throw an error.
MIT License. See theLICENSE file.You can use Hashids in open source projects and commercial products.Don't break the Internet. Kthxbye.
About
A small JavaScript library to generate YouTube-like ids from numbers.
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.
