hapi-hashids
Hapi.js plugin wrapper for hashids.
Installation
- In your Hapi.js project install hapi-hashids:
npm install --save hapi-hashids
- Register the plugin with your
server
object:
server.register({
register: require('hapi-hashids'),
options: {
salt: 'this is my salt',
minHashLength: 0,
alphabet: 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890',
}
}, (err) => {
if (err) {
throw err;
}
});
Usage
Once hapi-hashids are registered with your server, you can make use of them anywhere the server object is accessible (such as request handlers - request.server
).
All examples below are from the Node.js hashids git repo, but are using the Hapi plugin attached to the server
object.
Configuration:
- The
salt
used is: this is my salt. minHashLength
and alphabet
were unspecified to use their defaults, unless otherwise stated.
Encoding one number
server.plugins['hapi-hashids'].encode(12345);
Decoding
server.plugins['hapi-hashids'].decode('NkK9');
Decoding with different salt
Decoding will not work if the salt is changed:
server.plugins['hapi-hashids'].decode('NkK9');
Encoding several numbers
server.plugins['hapi-hashids'].encode(683, 94108, 123, 5);
Or pass as an array:
const arr = [683, 94108, 123, 5]
server.plugins['hapi-hashids'].encode(arr);
Decoding into several numbers
server.plugins['hapi-hashids'].decode('aBMswoO2UB3Sj');
Using minHashLength
We set the minimum id length to 8 (by default it is 0 -- meaning ids will be the shortest possible length).
server.register({
register: require('hapi-hashids'),
options: {
salt: 'this is my salt',
minHashLength: 0,
}
}, (err) => {
if (err) {
throw err;
}
server.plugins['hapi-hashids'].encode(1);
server.plugins['hapi-hashids'].decode('gB0NV05e');
});
Specifying custom alphabet
Here we set the alphabet to consist of valid hex characters: 0123456789abcdef
server.register({
register: require('hapi-hashids'),
options: {
salt: 'this is my salt',
alphabet: '0123456789abcdef',
}
}, (err) => {
if (err) {
throw err;
}
server.plugins['hapi-hashids'].encode(1234567);
server.plugins['hapi-hashids'].decode('b332db5');
});
Hex encoding/decoding
Hashids also support encoding and decoding of hex values, not only integers:
server.plugins['hapi-hashids'].encodeHex('507f191e810c19729de860ea');
server.plugins['hapi-hashids'].decodeHex('yNyaoWeKWVINWqvaM9bw');
Security notice
Hashids are used when you do not want to expose integer ids to the user. They should not be used for security purposes and are only meant as an algorithm to obfuscate numbers to give YouTube and Bit.ly style identifiers.
Read more on the official documentation page.