All Projects → niieani → Hashids.js

niieani / Hashids.js

Licence: mit
A small JavaScript library to generate YouTube-like ids from numbers.

Programming Languages

javascript
184084 projects - #8 most used programming language
typescript
32286 projects
shell
77523 projects

Projects that are alternatives of or similar to Hashids.js

hashids.pm
Hashids, ported for Perl
Stars: ✭ 15 (-99.57%)
Mutual labels:  encoding, hashids, hash, ids, database-ids
harsh
Hashids implementation in Rust
Stars: ✭ 48 (-98.64%)
Mutual labels:  encoding, hashids, hash, ids, database-ids
Hashids
A small PHP library to generate YouTube-like ids from numbers. Use it when you don't want to expose your database ids to the user.
Stars: ✭ 4,596 (+30.38%)
Mutual labels:  hash, ids, hashids, encoding, database-ids
Hermes
Client-side messaging channel for sending data from one browser tab to another
Stars: ✭ 111 (-96.85%)
Mutual labels:  hacktoberfest, npm-package
Name That Hash
🔗 Don't know what type of hash it is? Name That Hash will name that hash type! 🤖 Identify MD5, SHA256 and 3000+ other hashes ☄ Comes with a neat web app 🔥
Stars: ✭ 540 (-84.68%)
Mutual labels:  hacktoberfest, hash
Mevn Cli
Light speed setup for MEVN(Mongo Express Vue Node) Apps
Stars: ✭ 696 (-80.26%)
Mutual labels:  hacktoberfest, npm-package
Inspirational Quotes
💡 A simple NPM Package which returns random Inspirational Quotes. Get your daily quote and stay motivated! ✌️ 🌸
Stars: ✭ 150 (-95.74%)
Mutual labels:  hacktoberfest, npm-package
Netlify Cms
A Git-based CMS for Static Site Generators
Stars: ✭ 14,776 (+319.18%)
Mutual labels:  hacktoberfest, npm-package
Node Virtualbox
A JavaScript Library for Interacting with VirtualBox
Stars: ✭ 231 (-93.45%)
Mutual labels:  hacktoberfest, npm-package
bytes-java
Bytes is a utility library that makes it easy to create, parse, transform, validate and convert byte arrays in Java. It supports endianness as well as immutability and mutability, so the caller may decide to favor performance.
Stars: ✭ 120 (-96.6%)
Mutual labels:  encoding, hash
id-mask
IDMask is a Java library for masking internal ids (e.g. from your DB) when they need to be published to hide their actual value and to prevent forging. It has support optional randomisation has a wide support for various Java types including long, UUID and BigInteger. This library bases its security on strong cryptographic primitives.
Stars: ✭ 39 (-98.89%)
Mutual labels:  hashids, database-ids
Secure Ls
🔒 Secure localStorage data with high level of encryption and data compression
Stars: ✭ 486 (-86.21%)
Mutual labels:  hacktoberfest, encoding
Goimagehash
Go Perceptual image hashing package
Stars: ✭ 391 (-88.91%)
Mutual labels:  hacktoberfest, hash
Packagephobia
⚖️ Find the cost of adding a new dependency to your project
Stars: ✭ 1,110 (-68.51%)
Mutual labels:  hacktoberfest, npm-package
Highlightjs Line Numbers.js
Line numbering plugin for Highlight.js
Stars: ✭ 323 (-90.84%)
Mutual labels:  hacktoberfest, npm-package
Hashlib4pascal
Hashing for Modern Object Pascal
Stars: ✭ 132 (-96.26%)
Mutual labels:  hash, encoding
idy
👓 An ID obfuscator for ActiveRecord
Stars: ✭ 15 (-99.57%)
Mutual labels:  hashids, hash
Codetective
a tool to determine the crypto/encoding algorithm used according to traces from its representation
Stars: ✭ 121 (-96.57%)
Mutual labels:  hash, encoding
youtube-playlist
❄️ Extract links, ids, and names from a youtube playlist
Stars: ✭ 73 (-97.93%)
Mutual labels:  npm-package, ids
laravel-hashid
HashId Implementation on Laravel Eloquent ORM
Stars: ✭ 23 (-99.35%)
Mutual labels:  hashids, hash

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.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].