Node.js — Calculate an MD5 Hash

Node.js comes with the crypto module that provides a lot of useful methods for data encryption and hashing. There’s a built-in function to calculate an MD5 hash for a given value.

This tutorial shows you how to hash a given string using the MD5 algorithm.

Node.js Series Overview

Calculate an MD5 Hash in Node.js

You can calculate an MD5 hash using Node.js’ createHash method. The createHash method returns a Hash instance providing methods to update the content that should be hashed. You must call the digest method to retrieve the final hash string:

import { createHash } from 'node:crypto'

 * Returns an MD5 hash for the given `content`.
 * @param {String} content
 * @returns {String}
function md5(content) {  
  return createHash('md5').update(content).digest('hex')

A quick reminder: security experts consider the MD5 algorithm as not secure anymore. Yet, applications still use MD5, e.g., for checksum calculations. We also use MD5 in @supercharge/inertia to version JavaScript assets based on the content of your manifest file.

Please use another hashing algorithm (like SHA256) if your use-case of MD5 may cause security concerns.

Enjoy hashing values in Node.js using the MD5 algorithm!

Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.