Lessons from open-source: Algorithm used to compute error.digest in Next.js
Ramu Narasinga
Posted on April 2, 2024
This lesson is picked Next.js source code. In this article, you will learn how error.digest is computed in Next.js.
Error.digest
The docs says “An automatically generated hash of the error thrown in a Server Component. It can be used to match the corresponding error in server-side logs.”
You match this digest on your server logs. Next.js shows only the digest to prevent sensitive information leaked to the client side.
Do check the following Stackoverflow questions:
- Next.js error in production mode — Digest: 1782794309
- https://stackoverflow.com/questions/76713709/what-is-a-digest-property
Let’s find out how Next.js automatically generates this hash for an error.
As you can see from the above code snippet, it uses a function named stringHash which is imported at the top of create-error-handler.tsx
import stringHash from 'next/dist/compiled/string-hash'
Next.js has a quite some packages bundled in a folder named compiled. string-hash is an npm package.
I checked the string-hash source code.
"use strict";
function hash(str) {
var hash = 5381,
i = str.length;
while(i) {
hash = (hash \* 33) ^ str.charCodeAt(--i);
}
/\* JavaScript does bitwise operations (like XOR, above) on 32-bit signed
\* integers. Since we want the results to be always positive, convert the
\* signed int to an unsigned by doing an unsigned bitshift. \*/
return hash >>> 0;
}
module.exports = hash;
The particular algorithm is quite similar to djb2, by Dan Bernstein and is available here.
It has 1.7M downloads per week on NPM. I wish, some day I write some library that gets this many downloads.
Conclusion
This is what Next.js docs say about error.digest — “An automatically generated hash of the error thrown in a Server Component. It can be used to match the corresponding error in server-side logs”.
I looked at the source code to find out that string-hash algorithm is used to automatically generate a hash like below:
err.digest = stringHash(
err.message + (errorInfo?.stack || err.stack || '')
).toString()
Further digging led me to discover that string-hash has about 17 lines of code with 1.7 million downloads per week on NPM. I wish, some day I write some library that gets this many downloads. I did write few npm packages that are not so popular.
Get free courses inspired by the best practices used in open source.
About me:
Website: https://ramunarasinga.com/
Linkedin: https://www.linkedin.com/in/ramu-narasinga-189361128/
Github: https://github.com/Ramu-Narasinga
Email: ramu.narasinga@gmail.com
Posted on April 2, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
April 2, 2024