Top Related Projects
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.
Implementation of hashids (http://hashids.org) in Python. Compatible with Python 2 and Python 3
Go (golang) implementation of http://www.hashids.org
Quick Overview
Hashids.js is a small JavaScript library that generates short, unique, non-sequential ids from numbers. It's useful for creating short URLs, obfuscating database IDs, or generating random strings. The library is designed to be lightweight and easy to use, with no dependencies.
Pros
- Simple and easy to use API
- Generates short, URL-safe ids
- Supports custom alphabets and salt
- Can encode multiple numbers into a single id
Cons
- Not suitable for security-critical applications (not a cryptographic hash)
- Limited customization options compared to more complex hashing algorithms
- May produce longer ids for very large numbers or multiple inputs
Code Examples
Generating a simple hash:
import Hashids from 'hashids';
const hashids = new Hashids();
const id = hashids.encode(1234);
console.log(id); // Output: 'kRNrpKlJ'
Decoding a hash:
const numbers = hashids.decode('kRNrpKlJ');
console.log(numbers); // Output: [1234]
Using custom salt and minimum length:
const hashids = new Hashids('my salt', 10);
const id = hashids.encode(1234, 5678);
console.log(id); // Output: 'QaZl3xJvWg'
Getting Started
-
Install the package:
npm install hashids
-
Import and use in your project:
import Hashids from 'hashids'; const hashids = new Hashids(); // Encode const id = hashids.encode(1234); // Decode const numbers = hashids.decode(id);
-
Customize as needed:
const hashids = new Hashids('my salt', 10, 'abcdefghijklmnopqrstuvwxyz');
Competitor Comparisons
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.
Pros of Hashids
- More actively maintained with recent updates
- Supports a wider range of programming languages
- Better documentation and examples
Cons of Hashids
- Slightly larger package size
- May have a steeper learning curve for beginners
- Less focused on JavaScript-specific optimizations
Code Comparison
hashids.js:
const Hashids = require('hashids');
const hashids = new Hashids();
const id = hashids.encode(1, 2, 3);
console.log(id); // Output: "o2fXhV"
Hashids:
const Hashids = require('hashids/cjs');
const hashids = new Hashids();
const id = hashids.encode([1, 2, 3]);
console.log(id); // Output: "o2fXhV"
The main difference in usage is that Hashids expects an array for encoding multiple numbers, while hashids.js accepts them as separate arguments.
Both libraries provide similar core functionality for generating short, unique IDs from numbers. The choice between them often depends on specific project requirements, language preferences, and the need for cross-language compatibility.
Implementation of hashids (http://hashids.org) in Python. Compatible with Python 2 and Python 3
Pros of hashids-python
- Native Python implementation, potentially better performance for Python projects
- Supports Python 2.7 and 3.3+, offering wider compatibility
- Includes type hints for improved code readability and IDE support
Cons of hashids-python
- Less frequent updates compared to hashids.js
- Smaller community and fewer contributors
Code Comparison
hashids-python:
from hashids import Hashids
hashids = Hashids(salt="this is my salt")
hash = hashids.encode(1, 2, 3)
numbers = hashids.decode(hash)
hashids.js:
const Hashids = require('hashids/cjs');
const hashids = new Hashids("this is my salt");
const hash = hashids.encode([1, 2, 3]);
const numbers = hashids.decode(hash);
Both implementations offer similar functionality and ease of use. The main differences lie in language-specific syntax and features. hashids-python benefits from Python's simplicity and readability, while hashids.js leverages JavaScript's ecosystem and widespread use in web development.
Go (golang) implementation of http://www.hashids.org
Pros of go-hashids
- Written in Go, offering better performance and concurrency support
- Provides a more idiomatic Go implementation
- Includes additional utility functions for custom alphabet and salt generation
Cons of go-hashids
- Less widely adopted compared to hashids.js
- Fewer community contributions and updates
- Limited cross-platform compatibility compared to JavaScript
Code Comparison
hashids.js:
const Hashids = require('hashids');
const hashids = new Hashids('my salt');
const id = hashids.encode(1, 2, 3);
const numbers = hashids.decode(id);
go-hashids:
import "github.com/speps/go-hashids"
hd := hashids.NewData()
hd.Salt = "my salt"
h, _ := hashids.NewWithData(hd)
id, _ := h.Encode([]int{1, 2, 3})
numbers, _ := h.DecodeWithError(id)
Both libraries provide similar functionality for encoding and decoding hashids. The main differences lie in the language-specific implementations and syntax. hashids.js offers a more straightforward API with a single constructor, while go-hashids separates the configuration (NewData) and instance creation (NewWithData) steps. The Go version also includes explicit error handling in its method signatures.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
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
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
-
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]
-
Encoding negative numbers is not supported.
-
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
-
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.
Top Related Projects
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.
Implementation of hashids (http://hashids.org) in Python. Compatible with Python 2 and Python 3
Go (golang) implementation of http://www.hashids.org
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot