SHA-256 Hashing in JavaScript: Web Crypto API Guide
Learn how to compute SHA-256 hashes in JavaScript using the Web Crypto API and Node.js crypto module. Includes working code examples.
SHA-256 (Secure Hash Algorithm 256-bit) is part of the SHA-2 family and produces a 64-character hexadecimal hash. In modern browsers and Node.js, SHA-256 is available through the Web Crypto API and the crypto built-in module respectively — no third-party libraries required. This makes it the standard choice for hashing in JavaScript applications.
How to Use the SHA-256 Generator Tool
- Enter your text — Type or paste the string you want to hash into the input field.
- Click Generate — The tool produces a 64-character SHA-256 hash.
- Copy the result — Use the copy button to grab the hash for your code or comparison.
- Use the code examples below — Implement the same hash in your JavaScript application using the browser Web Crypto API or Node.js.
SHA-256 in the Browser (Web Crypto API)
async function sha256(message) {
const encoder = new TextEncoder();
const data = encoder.encode(message);
const hashBuffer = await crypto.subtle.digest('SHA-256', data);
const hashArray = Array.from(new Uint8Array(hashBuffer));
const hashHex = hashArray
.map(b => b.toString(16).padStart(2, '0'))
.join('');
return hashHex;
}
// Usage:
sha256('hello world').then(hash => {
console.log(hash);
// b94d27b9934d3e08a52e52d7da7dabfac484efe04294e576b94...
});
SHA-256 in Node.js
const crypto = require('crypto');
function sha256(input) {
return crypto
.createHash('sha256')
.update(input, 'utf8')
.digest('hex');
}
console.log(sha256('hello world'));
// b94d27b9934d3e08a52e52d7da7dabfac484efe04294e576b94...
Why Use SHA-256 in JavaScript?
- No dependencies — The Web Crypto API is built into all modern browsers. No npm packages needed for basic hashing.
- Async-friendly —
crypto.subtle.digest()returns a Promise, fitting naturally into async/await patterns. - Strong collision resistance — With 2^256 possible outputs, SHA-256 is practically collision-free for real-world use.
- Consistent output — The same input always produces the same 64-character hex string across all platforms and languages.
SHA-256 for Data Integrity in JavaScript Apps
A common pattern is to hash API request bodies or file contents before sending them, then verify on the server that the hash matches. This confirms the payload was not altered in transit. Another use case is generating deterministic identifiers from content — for example, hashing a URL to produce a cache key for a service worker.
Test SHA-256 hashes instantly with the SHA-256 Generator before embedding them in your JavaScript code.