92

Our application kept showing the error in the title. The problem is very likely related to Webpack 5 polyfill and after going through a couple of solutions:

  1. Setting fallback + install with npm
fallback: {
  "stream": require.resolve("stream-browserify"),
  "buffer": require.resolve("buffer/")
}
  1. Setting alias
alias: {
  "buffer": "buffer",
  "stream": "stream-browserify"
}

We are still seeing the dreadful error:

rfc6979.js:3 Uncaught ReferenceError: Buffer is not defined
    at Object.4142 (rfc6979.js:3)
    at r (bootstrap:19)
    at Object.5892 (js.js:4)
    at r (bootstrap:19)
    at Object.4090 (bip32.js:5)
    at r (bootstrap:19)
    at Object.7786 (index.js:3)
    at r (bootstrap:19)
    at Object.1649 (MnemonicKey.js:50)
    at r (bootstrap:19)

Our setup is vanilla NodeJS + TypeScript + Webpack for multi-target: node + browser. Any help would be great!

14 Answers 14

97

Answering my own question. Two things helped to resolve the issue:

  1. Adding plugins section with ProviderPlugin into webpack.config.js
const webpack = require('webpack');

module.exports = {
    // ...

    plugins: [
        // Work around for Buffer is undefined:
        // https://github.com/webpack/changelog-v5/issues/10
        new webpack.ProvidePlugin({
            Buffer: ['buffer', 'Buffer'],
        }),
        new webpack.ProvidePlugin({
            process: 'process/browser',
        }),
    ],

  1. Also add in resolve.fallback into webpack.config.js:
    resolve: {
        extensions: [ '.ts', '.js' ],
        fallback: {
            "stream": require.resolve("stream-browserify"),
            "buffer": require.resolve("buffer")
        }
    },

4
  • 3
    I am using react-scripts 5 and this solution doesnt work for me. I tried to use react-app-rewired to add config-overrides.js as described. But app still doesnt find buffer
    – tonisives
    Feb 1, 2022 at 10:01
  • 3
    Note @tonisives that you may need to clear your cache after this change - rm -fr node_modules/.cache
    – jfrumar
    Feb 1, 2022 at 21:01
  • 1
    Thanks! I managed to fix it by adding yarn add process Here is my full overview github.com/terra-money/terra.js/issues/223
    – tonisives
    Feb 2, 2022 at 0:11
  • hello @whileone -- this helped my use case, but by any chance do you know why this works and wasnt needed in Webpack 4? Why in Webpack 5? -- its been a nightmare fixing breaking changes
    – nsun
    Jul 14 at 16:27
63

I've tried all the answers here to resolve this issue and nothing worked for me. What did work for me was putting the following in my polyfills.ts:

import { Buffer } from 'buffer';

// @ts-ignore
window.Buffer = Buffer;

and of course, npm install --save buffer

3
  • 1
    Great! This works independent of the framework used. May 30, 2022 at 17:33
  • 4
    I was using Buffer on a single file. By just importing and setting window.Buffer on that single file fixed the problem for me without creating the polyfills.ts file. Jun 3, 2022 at 1:27
  • If you use React with Vite and don't have any polyfill files - add it somewhere in the root of your app. For example in App.jsx or in main.jsx Oct 20 at 11:43
41

Everyone who came here because of react-scripts (5.0.0) (@whileons answer is correct, this is only the configuration for react-scripts):

First, add these dependencies to your package.json:

"buffer": "^6.0.3",
"process": "^0.11.10",
"stream-browserify": "^3.0.0"
"react-app-rewired": "^2.2.1" --dev

Update your package.json scripts.

Before:

"scripts": {
    "debug": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
},

After

  "scripts": {
    "debug": "react-app-rewired start",
    "build": "react-app-rewired build",
    "test": "react-app-rewired test",
    "eject": "react-app-rewired eject"
  },

Create a file config-overrides.js in the root folder (NOT under src, in the same folder like your package.json) and paste the following code inside:

const webpack = require("webpack")

module.exports = function override(config, env) {
    //do stuff with the webpack config...
    config.resolve.fallback = {
        ...config.resolve.fallback,
        stream: require.resolve("stream-browserify"),
        buffer: require.resolve("buffer"),
    }
    config.resolve.extensions = [...config.resolve.extensions, ".ts", ".js"]
    config.plugins = [
        ...config.plugins,
        new webpack.ProvidePlugin({
            process: "process/browser",
            Buffer: ["buffer", "Buffer"],
        }),
    ]
    // console.log(config.resolve)
    // console.log(config.plugins)

    return config
}

Dont forget to delete node_modules and npm install it again.

3
  • 2
    This seems to work for me. Just wanted to point out the file name needs to be config-overrides.js (plural) Feb 25, 2022 at 18:20
  • 2
    Very helpful, I forgot to follow the last line Delete node_modules. But finally deleted node_modules and installed again to get things running.
    – Learner
    Mar 30, 2022 at 0:57
  • Thank you. One thing that threw me - is that I was using "yarn start" - and in your version, you have "debug" as the name of the start script - so "start" wasn't working. I changed it to "start" and everything worked as expected. Just noting this in case others also fall down that rabbit hole.
    – Korimako
    Jul 31, 2022 at 6:04
14

This worked for me

npm install --save buffer

Then in the file where I was using buffer

import { Buffer } from 'buffer';

I guess it wasn't installed, but my IDE already had type descriptions for it? Idk

1
  • Is there some way to install this globally? Like how you no longer need to import React to use React functionality? I don't understand how/why we no longer need to import React but if we could use the same tecnhnique with Buffer, I would not need to import it - and I need to import it into my node_modules/mqtt-packet/constants file to make my mqtt-react-hooks package useable. May 6 at 20:52
11

What worked for me is the following:

First:

npm install --save buffer

Then:

// webpack.config.js
const webpack = require("webpack");

module.exports = {
  plugins: [
    new webpack.ProvidePlugin({
      Buffer: ['buffer', 'Buffer'],
    }),
    // ..
  ]
  // ..
}
0
6

I was getting the same error, and this is how I solved the problem.

First:

npm install --save buffer

Then:

Added this to my app.tsx file.

window.Buffer = window.Buffer || require("buffer").Buffer;
0
4

Additional detail for VueJS developers,
this answer worked and my vue.config.js file was like this.

const { defineConfig } = require('@vue/cli-service')
const webpack = require('webpack');

module.exports = defineConfig({
  transpileDependencies: true,
  configureWebpack: {
  plugins: [
    // Work around for Buffer is undefined:
    // https://github.com/webpack/changelog-v5/issues/10
    new webpack.ProvidePlugin({
      Buffer: ['buffer', 'Buffer'],
    })
  
  ],
  resolve: {
    extensions: ['.ts', '.js'],
    fallback: {
      "stream": require.resolve("stream-browserify"),
      "buffer": require.resolve("buffer")
    }
  },
 }
})

I deleted my node_modules folder and ran npm install again.

2
  • TypeError: defineConfig is not a function Nov 24, 2022 at 13:11
  • What webpack, vue, and npm versions are you using? vue 3 with webpack 5.88.2 and npm 9.8.1 causes a TypeError in `webpack\lib\compilation.js`?
    – luke
    Sep 26 at 4:05
3

You could also just install the following library: https://github.com/feross/buffer

yarn add buffer

2

While everyone is suggesting to install polyfill, there is a native way in NodeJS to do this, per their documentation

import { Buffer } from 'node:buffer'

If you are using this in NodeJs, including Webpack, and not in the browser, this is the preferred solution.

1

I've found a bug when I tried to use TonWebSDK with create-react-app and found a fix for that.

After project setup with npx create-react-app my-app I imported tonweb from 'tonweb' but faced an error Uncaught ReferenceError: Buffer is not defined.

I run npm run eject in order to modify the webpack config. I added Buffer support to the plugins of webpack with next lines:

 new webpack.ProvidePlugin({
          Buffer: ['buffer', 'Buffer'],
        })

And this worked for me.

0

Downgrading react-scripts to 4.0.3 worked https://github.com/terra-money/terra.js/issues/223. It may not be the optimal solution, but it was the only thing that worked for me.

2
  • Check answer of @parliament here
    – fl-web
    Jun 23, 2022 at 6:57
  • That really isn't a solution, as there are more and more security issues with the dependencies pulled in by CRA 4.
    – TheDiveO
    Feb 28 at 14:55
0

It turns out that there is third-party plugin that provides all node.js polyfills (not just Buffer) out of the box: node-polyfill-webpack-plugin.

It brings all polyfills as its own dependancies, so you should use excludeAliases config property to define what polyfills you do not want to be included.

0

Install casbin.js@^1.0.1 instead of casbin.

0

The CSS minimizer in Webpack 5 is more strict about what is allowed in the CSS files. You likely have a misplaced / somewhere in your CSS.

For instance, it does not like // comments: // This will break

Also, check for slashes in any className paths, e.g.: .myDiv/otherDiv

Removing these will solve your problem and allow you to keep your optimized CSS. Replace any comments using the /* */ syntax. Also check to make sure those are well-formed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.