DEV Community

Cover image for Lessons from open-source: Algorithm used to compute error.digest in Next.js
Ramu Narasinga
Ramu Narasinga

Posted on

Lessons from open-source: Algorithm used to compute error.digest in Next.js

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:

  1. Next.js error in production mode — Digest: 1782794309
  2. https://stackoverflow.com/questions/76713709/what-is-a-digest-property

Let’s find out how Next.js automatically generates this hash for an error.

error.digest

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

Practice the exercises based on documentation to become an expert in Next.js.

import stringHash from 'next/dist/compiled/string-hash'
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)