Generate a hash from a string in NodeJS
NicolasBrondinBernard
Learn how to create a hash (SHA-256) from a string, in a single line of code!

Article published on 30/10/2023, last updated on 10/08/2026
It's very easy to create a hash in NodeJS, but it requires using three methods (createHash, update and digest) from the crypto module, which can make the task more confusing than in other languages.
Here's how to use them:
import { createHash } from 'node:crypto'
const str = "hello";
const hash = createHash('sha256').update(str).digest('hex');
Result:
2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
And there you go, your hash is ready!
Be careful, remember that when you hash a piece of information, you can't go back! (Hashing ≠ Encryption)
Important information
If you're using this method to hash a password, know that you need to add a grain of salt for more security!
If you're not familiar with storing passwords in a database, read our dedicated article to find out what to do and what NOT to do.
No spam. Only free content, news, and ever more resources to level up your skills!
Join +1500 developers
No comments yet