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

Package detail

hashids

niieani640.8kMIT2.3.0TypeScript support: included

Generate YouTube-like ids from numbers. Use Hashids when you do not want to expose your database ids to the user.

hashids, hashid, hash, ids, youtube, bitly, obfuscate, encode, decode, encrypt, decrypt

readme

hashids

Build Status Coveralls Status NPM downloads NPM version License Chat

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

Play with it using CodeSandbox

Getting started

Install Hashids via:

yarn add hashids

(or just directly use the code at dist/hashids.js)

Use in ESM-compatible environments (webpack, modern browsers)

import Hashids from 'hashids'
const hashids = new Hashids()

console.log(hashids.encode(1))

Use in CommonJS environments (most often Node.js)

const Hashids = require('hashids/cjs')
const hashids = new Hashids()

console.log(hashids.encode(1))

Note: When using Node that supports conditional exports, require('hashids') (version >=13) will also work.

Use as global in the browser (wherever ES6 is supported; 5KB)

<script type="text/javascript" src="hashids.min.js"></script>
<script type="text/javascript">

    var hashids = new Hashids();
    console.log(hashids.encode(1));

</script>

Use in TypeScript:

import or require, 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 the DefinitelyTyped repository.

npm install @types/node

If you want to use the ESM syntax (import Hashids from 'hashids'), you will need to include the following options in your tsconfig.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 your tsconfig.json file, under "lib":

{
  "compilerOptions": {
    ...
    "lib": [
      "esnext.bigint",
      ...
    ]
  }
}

Note that your environment doesn't actually have to support BigInt for hashids to function.

Quick example

const hashids = new Hashids()

const id = hashids.encode(1, 2, 3) // o2fXhV
const numbers = hashids.decode(id) // [1, 2, 3]

More options

A few more ways to pass to encode():

const hashids = new Hashids()

console.log(hashids.encode(1, 2, 3)) // o2fXhV
console.log(hashids.encode([1, 2, 3])) // o2fXhV
// strings containing integers are coerced to numbers:
console.log(hashids.encode('1', '2', '3')) // o2fXhV
console.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):

var hashids = new Hashids('My Project')
console.log(hashids.encode(1, 2, 3)) // Z4UrtW

var hashids = new Hashids('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 fit at least a certain length. It doesn't mean that your ids will be exactly that length.

const hashids = new Hashids() // no padding
console.log(hashids.encode(1)) // jR

const hashids = new Hashids('', 10) // pad to length 10
console.log(hashids.encode(1)) // VolejRejNm

Pass a custom alphabet:

const hashids = new Hashids('', 0, 'abcdefghijklmnopqrstuvwxyz') // all lowercase
console.log(hashids.encode(1, 2, 3)) // mdfphx

Default alphabet is abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.

Since v2.0 you can even use emojis as the alphabet.

Encode hex instead of numbers:

Useful if you want to encode numbers like Mongo's ObjectIds.

Note that there is no limit on how large of a hex number you can pass.

var hashids = new Hashids()

var id = hashids.encodeHex('507f1f77bcf86cd799439011') // y42LW46J9luq3Xq9XMly
var hex = hashids.decodeHex(id) // 507f1f77bcf86cd799439011

Please note that this is not the equivalent of:

const hashids = new Hashids()

const id = Hashids.encode(BigInt('0x507f1f77bcf86cd799439011')) // y8qpJL3ZgzJ8lWk4GEV
const hex = Hashids.decode(id)[0].toString(16) // 507f1f77bcf86cd799439011

The difference between the two is that the built-in encodeHex will always result in the same length, even if it contained leading zeros.

For example hashids.encodeHex('00000000') would encode to qExOgK7 and decode back to '00000000' (length information is preserved).

Pitfalls

  1. When decoding, output is always an array of numbers (even if you encode only one number):

    const hashids = new Hashids()
    
    const id = hashids.encode(1)
    console.log(hashids.decode(id)) // [1]
  2. Encoding negative numbers is not supported.

  3. If you pass bogus input to encode(), an empty string will be returned:

    const hashids = new Hashids()
    
    const id = hashids.encode('123a')
    console.log(id === '') // true
  4. Do not use this library as a security tool and do not encode sensitive data. This is not an encryption library.

Randomness

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:

const hashids = new Hashids()
console.log(hashids.encode(5, 5, 5)) // A6t1tQ

Same with incremented numbers:

const hashids = new Hashids()

console.log(hashids.encode(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) // wpfLh9iwsqt0uyCEFjHM

console.log(hashids.encode(1)) // jR
console.log(hashids.encode(2)) // k5
console.log(hashids.encode(3)) // l5
console.log(hashids.encode(4)) // mO
console.log(hashids.encode(5)) // nR

Curses! #$%@

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, u

You 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)
const hashids = new Hashids(undefined, undefined, undefined, 'zyxZYX')

BigInt

If your environment supports BigInt, you can use the standard API to encode and decode them the same way as ordinary numbers.

Trying to decode a BigInt-encoded hashid on an unsupported environment will throw an error.

License

MIT License. See the LICENSE file. You can use Hashids in open source projects and commercial products. Don't break the Internet. Kthxbye.

changelog

CHANGELOG

2.0.0:

This is pretty much a TypeScript rewrite.

Breaking changes

  • BREAKING CHANGE: Hashids now throws errors when being constructed with incorrect options (previously, it silently falled back to defaults)
  • BREAKING CHANGE: when used from Node (without ESM enabled), you now need to require('hashids/cjs')

Features

  • transparent support of BigInts. If your environment supports them, you can use the standard API to encode and decode them. Note that trying to decode a BigInt hashid on an unsupported environment will throw an error.
  • lifted the limitation that the alphabet cannot containin spaces
  • both the alphabet and salt may now contain multi-byte characters (e.g. for an emoji-based alphabet)

Chores

  • upgraded all dependencies
  • tests now use jest testing framework
  • extracted static methods to helper functions
  • converted the implementation to TypeScript
  • added prettier
  • added stricter eslint rules

1.2.2:

1.2.1 (do not use):

1.2.0 (do not use):

  • drop unsupported node versions (6 and above is still supported)
  • drop support for browsers with global market share < 0.5%
  • upgrade to babel 7 and update other devDependencies
  • expose both as a default and a commonjs export (fixes TypeScript typings)
  • add support for .mjs
  • package.json updates
  • .gitattributes marks package-lock.json as binary
  • path of the source file changed from dist/hashids.min.map to dist/hashids.min.js.map
  • minor regex cleanup
  • precommit hook to run lint and test

1.1.4:

1.1.2:

  • fixed issue with sourceMappingURL in hashids.min.js (PR #38)
  • added package-lock.json

1.1.1:

  • Enforce stricter integer parsing on encode function (PR #24)
  • Moved source from hashids.js to lib/hashids.js
  • Minor README.md cleanup

1.1.0:

  • ES6 source; ES5 dist
  • UMD support (Node.js repo is merging into this one)
  • Added Eslint (npm run lint)
  • Added Mocha (npm run test)
  • Added Coveralls (npm run coverage)
  • Added build script (npm run build)
  • Moved CHANGELOG out of README.md
  • README.md completely updated
  • examples/ folder removed; all examples are now in the README
  • Bug fix: escaping regex
  • Improvement: relaxed parameter checks to encode(). All of these are allowed:

        ```javascript
        var hashids = new Hashids();
    
        hashids.encode(1, 2, 3); // o2fXhV
        hashids.encode([1, 2, 3]); // o2fXhV
        hashids.encode('1', '2', '3'); // o2fXhV
        hashids.encode(['1', '2', '3']); // o2fXhV
        ```

1.0.2:

1.0.1:

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()

        Hashids was designed to encode integers, primary ids at most. We've had several requests to encrypt sensitive data with Hashids and this is the wrong algorithm for that. So to encourage more appropriate use, `encrypt/decrypt` is being "downgraded" to `encode/decode`.
  • Version tag added: 1.0

  • README.md updated

0.3.0:

PRODUCED HASHES IN THIS VERSION ARE DIFFERENT THAN IN 0.1.4, DO NOT UPDATE IF YOU NEED THEM TO KEEP WORKING:

  • Same algorithm as PHP and Node.js versions now
  • Overall approximately 4x faster
  • Consistent shuffle function uses slightly modified version of Fisher–Yates algorithm
  • Generate large hash strings faster (where minHashLength is more than 1000 chars)
  • When using minHashLength, hash character disorder has been improved
  • Basic English curse words will now be avoided even with custom alphabet
  • encrypt function now also accepts array of integers as input
  • Passing JSLint now
  • Support for Bower package manager

0.1.4:

0.1.3:

Warning: If you are using 0.1.2 or below, updating to this version will change your hashes.
  • Updated default alphabet (thanks to @speps)
  • Constructor removes duplicate characters for default alphabet as well (thanks to @speps)

0.1.2:

Warning: If you are using 0.1.1 or below, updating to this version will change your hashes.
  • Minimum hash length can now be specified
  • Added more randomness to hashes
  • Added unit tests
  • Added example files
  • Changed warnings that can be thrown
  • Renamed encode/decode to encrypt/decrypt
  • Consistent shuffle does not depend on md5 anymore
  • Speed improvements

0.1.1:

  • Speed improvements
  • Bug fixes

0.1.0:

  • First commit