TypeScript MD5 Hashing Library
ts-md5 is a TypeScript-first implementation of the MD5 hashing algorithm, designed for both Node.js (>=18) and browser environments. It provides functionalities for hashing Unicode and ASCII strings, supporting incremental hashing, and directly processing Files and Blobs. The library also includes advanced features like a `ParallelHasher` that leverages web workers for asynchronous file/blob hashing, improving performance in browser contexts. Its current stable version is 2.0.1, with releases showing active maintenance, including a recent major update to v2.0.0 in July 2025 that shifted to Vite for bundling. Key differentiators include its strong TypeScript typing, robust handling of various input types (strings, byte arrays, files), and built-in web worker support for computationally intensive tasks, making it a versatile choice for applications requiring MD5 checksums. It builds upon established MD5 implementations by Joseph Myers, André Cruz (SparkMD5), and Raymond Hill (yamd5.js).
Common errors
-
Error [ERR_REQUIRE_ESM]: require() of ES Module ...ts-md5/dist/md5.js not supported. Instead change the require of ...md5.js to a dynamic import() call.
cause Attempting to import `ts-md5` using CommonJS `require()` syntax in a Node.js environment or bundler that strictly enforces ESM for `ts-md5` v2.0.0 and above.fixUpdate your import statements to use ESM `import { Md5 } from 'ts-md5';`. If your project is CommonJS, consider setting `"type": "module"` in your `package.json` or configuring your bundler to transpile ESM for CJS consumption. -
Uncaught DOMException: Failed to construct 'Worker': Script at 'http://localhost:3000/md5_worker.js' cannot be accessed from origin 'http://localhost:3000'.
cause The web worker script (`md5_worker.js`) required by `ParallelHasher` is not found at the specified URL, or there's a CORS issue preventing its loading.fixEnsure `md5_worker.js` (from `node_modules/ts-md5/dist/`) is copied to your public assets directory by your build system. Then, provide the correct, publicly accessible URL to the `ParallelHasher` constructor (e.g., `new ParallelHasher('/assets/md5_worker.js')`). -
TypeError: Md5.hashStr is not a function
cause This error typically occurs if `Md5` is imported incorrectly (e.g., as a default import instead of a named export) or if you are trying to call `hashStr` on an instance of `Md5` instead of the static class itself.fixVerify that you are importing `Md5` as a named export: `import { Md5 } from 'ts-md5';`. Then, call `Md5.hashStr()` directly on the class name, as it is a static method.
Warnings
- breaking Version 2.0.0 introduced a significant change by updating the project to use Vite for bundling. This likely shifts the package to an ESM-first or ESM-only distribution, which can break existing CommonJS (`require()`) imports in older Node.js environments or projects without proper bundler configuration.
- gotcha When using `ParallelHasher` in a browser environment, the `md5_worker.js` file (located in `ts-md5/dist/`) must be publicly accessible via a URL. Your build process needs to copy this file to your public assets, and the path provided to the `ParallelHasher` constructor must reflect this public URL.
- gotcha MD5 is a cryptographically broken hash function and should NOT be used for security-sensitive applications such as password storage, digital signatures, or generating secure tokens. It is vulnerable to collision attacks.
- gotcha The static methods `Md5.hashStr()` and `Md5.hashAsciiStr()` accept an optional second argument. If `true` is passed, the method returns a raw `Int32Array(4)` instead of the default hexadecimal string. This can lead to unexpected type mismatches if not explicitly handled or if a hex string is always expected.
Install
-
npm install ts-md5 -
yarn add ts-md5 -
pnpm add ts-md5
Imports
- Md5
const Md5 = require('ts-md5').Md5; import Md5 from 'ts-md5';import { Md5 } from 'ts-md5'; - ParallelHasher
const { ParallelHasher } = require('ts-md5');import { ParallelHasher } from 'ts-md5'; - Md5.hashStr
import Md5 from 'ts-md5'; Md5.hashStr('some string'); new Md5().hashStr('some string');import { Md5 } from 'ts-md5'; Md5.hashStr('some string');
Quickstart
import { Md5, ParallelHasher } from 'ts-md5';
// Basic synchronous hashing
console.log('--- Basic Hashing ---');
const hexHash1 = Md5.hashStr('hello world');
console.log(`'hello world' (hex): ${hexHash1}`);
const rawHash1 = Md5.hashStr('hello world', true);
console.log(`'hello world' (raw Int32Array): ${rawHash1}`);
const asciiHash = Md5.hashAsciiStr('simple ascii');
console.log(`'simple ascii' (ascii hex): ${asciiHash}`);
// Incremental hashing
console.log('\n--- Incremental Hashing ---');
const md5Instance = new Md5();
md5Instance
.appendStr('first part of the string ')
.appendAsciiStr('second part')
.appendStr(' and a final piece');
const incrementalHash = md5Instance.end();
console.log(`Incremental hash: ${incrementalHash}`);
// Example for hashing a Blob (requires a Blob instance, mocking for quickstart)
// In a real scenario, 'fileBlob' would come from an <input type="file"> event or similar.
async function hashBlobExample() {
console.log('\n--- Hashing a Blob (ParallelHasher) ---');
if (typeof Worker === 'undefined') {
console.warn('Web Workers not available in this environment. Skipping ParallelHasher example.');
return;
}
// Mocking a Blob
const mockBlob = new Blob(['This is some content for the blob to be hashed.'], { type: 'text/plain' });
// NOTE: Replace '/path/to/ts-md5/dist/md5_worker.js' with the actual URL where your worker script is served.
// This typically means configuring your build tool (e.g., Vite, Webpack) to copy this file to your public directory.
const workerPath = '/ts-md5/dist/md5_worker.js'; // Example relative path in a public folder
let hasher: ParallelHasher | undefined;
try {
hasher = new ParallelHasher(workerPath);
const result = await hasher.hash(mockBlob);
console.log(`MD5 of mockBlob is: ${result}`);
} catch (error) {
console.error(`Error hashing blob with ParallelHasher: ${error}. Make sure '${workerPath}' is accessible.`);
} finally {
// Important: Terminate the worker to release resources
hasher?.terminate();
}
}
hashBlobExample();