Generate hashes from javascript objects in node and the browser.
npx @tessl/cli install tessl/npm-object-hash@3.0.0Object Hash is a robust JavaScript library that generates consistent hash values from any JavaScript object, value, or data structure. It works in both Node.js and browser environments, supporting multiple hash algorithms and extensive configuration options for deterministic object serialization.
npm install object-hashconst hash = require('object-hash');ES6/ESM:
import hash from 'object-hash';Browser (UMD):
<script src="object_hash.js"></script>
<script>
const hashValue = objectHash.sha1({foo: 'bar'});
</script>const hash = require('object-hash');
// Basic object hashing
const obj = { name: 'John', age: 30, city: 'New York' };
const hashValue = hash(obj);
console.log(hashValue); // => "67b69634f9880a282c14a0f0cb7ba20cf5d677e9"
// Hash arrays
const arr = [1, 2, 2.718, 3.14159];
const arrayHash = hash(arr);
console.log(arrayHash); // => "136b9b88375971dff9f1af09d7356e3e04281951"
// Different algorithms and encodings
const md5Hash = hash(obj, { algorithm: 'md5', encoding: 'base64' });
console.log(md5Hash); // => "6rkWaaDiG3NynWw4svGH7g=="Generate a hash from any object or type with extensive configuration options.
/**
* Generate a hash from any object or type
* @param {any} object - Value to hash
* @param {HashOptions} options - Optional hashing configuration
* @returns {string} Hash value
*/
function hash(object, options);
interface HashOptions {
/** Hash algorithm: 'sha1', 'md5', 'passthrough', or any crypto.getHashes() result (default: 'sha1') */
algorithm?: string;
/** Hash encoding: 'buffer', 'hex', 'binary', 'base64' (default: 'hex') */
encoding?: string;
/** Hash object keys only, ignore values (default: false) */
excludeValues?: boolean;
/** Ignore unknown object types (default: false) */
ignoreUnknown?: boolean;
/** Optional function that replaces values before hashing */
replacer?: (value: any) => any;
/** Consider function properties when hashing (default: true) */
respectFunctionProperties?: boolean;
/** Consider 'name' property of functions for hashing (default: true) */
respectFunctionNames?: boolean;
/** Respect special type attributes (.prototype, .__proto__, .constructor) (default: true) */
respectType?: boolean;
/** Sort all arrays before hashing (default: false) */
unorderedArrays?: boolean;
/** Sort Set and Map instances before hashing (default: true) */
unorderedSets?: boolean;
/** Sort objects before hashing (default: true) */
unorderedObjects?: boolean;
/** Optional function for excluding specific keys from hashing */
excludeKeys?: (key: string) => boolean;
}Usage Examples:
const hash = require('object-hash');
// Basic usage with default SHA-1
const basicHash = hash({ foo: 'bar', baz: 42 });
// Custom algorithm and encoding
const customHash = hash(
{ user: 'alice', role: 'admin' },
{ algorithm: 'md5', encoding: 'base64' }
);
// Exclude specific keys
const filteredHash = hash(
{ name: 'John', password: 'secret', email: 'john@example.com' },
{
excludeKeys: function(key) {
return key === 'password';
}
}
);
// Hash only keys, ignore values
const keysOnlyHash = hash(
{ name: 'Alice', age: 25 },
{ excludeValues: true }
);
// Unordered arrays (sort before hashing)
const unorderedHash = hash(
{ tags: ['javascript', 'nodejs', 'hash'] },
{ unorderedArrays: true }
);Hash using the SHA-1 algorithm (equivalent to default behavior).
/**
* Hash using the SHA-1 algorithm
* @param {any} object - Value to hash
* @returns {string} SHA-1 hash value
*/
hash.sha1(object);Usage Example:
const sha1Hash = hash.sha1({ data: 'example' });
// Equivalent to: hash({ data: 'example' }, { algorithm: 'sha1' })Hash object keys using SHA-1, ignoring values.
/**
* Hash object keys using SHA-1, values ignored
* @param {any} object - Value to hash
* @returns {string} Hash of keys only
*/
hash.keys(object);Usage Example:
const user1 = { name: 'Alice', age: 25, city: 'NYC' };
const user2 = { name: 'Bob', age: 30, city: 'LA' };
const keysHash1 = hash.keys(user1);
const keysHash2 = hash.keys(user2);
// Both return the same hash since they have the same keysHash using the MD5 algorithm.
/**
* Hash using the MD5 algorithm
* @param {any} object - Value to hash
* @returns {string} MD5 hash value
*/
hash.MD5(object);Usage Example:
const md5Hash = hash.MD5({ data: 'example' });
// Equivalent to: hash({ data: 'example' }, { algorithm: 'md5' })Hash object keys using MD5, ignoring values.
/**
* Hash object keys using MD5, values ignored
* @param {any} object - Value to hash
* @returns {string} MD5 hash of keys only
*/
hash.keysMD5(object);Usage Example:
const structure = { id: 1, name: 'test', metadata: { created: Date.now() }};
const structureHash = hash.keysMD5(structure);
// Returns MD5 hash of the object structure (keys only)Write the information that would otherwise have been hashed to a stream.
/**
* Write the information that would otherwise have been hashed to a stream
* @param {any} object - Value to serialize
* @param {HashOptions} options - Optional hashing configuration (optional)
* @param {Stream} stream - A stream to write the serialization to
* @returns {void}
*/
hash.writeToStream(object, options, stream);
// Alternative signature when options are omitted:
hash.writeToStream(object, stream);Usage Example:
const hash = require('object-hash');
// Write to stdout
hash.writeToStream(
{ foo: 'bar', num: 42 },
{ respectType: false },
process.stdout
);
// Outputs: "object:foo:string:barnum:number:42"
// Write to a custom stream
const fs = require('fs');
const writeStream = fs.createWriteStream('./output.txt');
hash.writeToStream({ data: 'example' }, writeStream);Object Hash can handle all JavaScript types including:
The library throws errors in the following situations:
Error('Object argument required.')Error('Algorithm "xyz" not supported. supported values: sha1, md5, ...')Error('Encoding "xyz" not supported. supported values: buffer, hex, binary, base64')Error('Unknown object type "xyz"') (unless ignoreUnknown: true)Error('Hashing Blob objects is currently not supported...') (unless using replacer or ignoreUnknown)Note: SHA-1 and MD5 are not considered cryptographically secure. Use stronger algorithms if cryptographic security is required.
const hash = require('object-hash');
// Cryptographically secure hash
const secureHash = hash(data, { algorithm: 'sha256' });
// Deterministic array hashing (order-independent)
const deterministicHash = hash(
{ items: [3, 1, 2] },
{ unorderedArrays: true }
);
// Function-aware hashing
const fnHash = hash(
{ handler: function myHandler() { return true; } },
{
respectFunctionNames: true,
respectFunctionProperties: true
}
);
// Custom serialization with replacer
const customHash = hash(data, {
replacer: function(value) {
if (value instanceof Date) {
return value.toISOString();
}
return value;
}
});
// Ignore unknown types instead of throwing
const safeHash = hash(data, { ignoreUnknown: true });