Search code examples
node.jswebpackcryptojs

NodeJS crypto module not working in browser after bundling with webpack


I keep getting the following error when I view my code in the browser:

Uncaught TypeError: crypto.createHash is not a function

I've tried loading the module during runtime using webpack:

module.exports = {
  target: "web",
  mode: "production",
  entry: "./dist/index.js",
  output: { filename: "../dist/bundle.js" },
  externals: { crypto: require("crypto") }, <=== here
};

and importing as: import * as crypto from "crypto", but this leads to the same error outlined above.

I realize that the browser has its own native crypto API and thus also tried aliasing the name to a different name like import * as crypt from "crypto", however this leads to the same error.

Repository with full code is available: https://www.github.com/lbragile/LibraCoin


Solution

  • Node.js core libraries are only available in node.js environments. So, if at the end, you will run your code in browser, you cannot use node core libraries.

    Note that crypto is a core library

    Browser crypto API is completely different as far as I know. So check out its docs