React Uncaught ReferenceError: Buffer is not defined

Viewed 11191

I created a React project by running npx create-react-app my-app

I installed mqtt-react-hooks

I added the App script

import { Connector } from 'mqtt-react-hooks';

import Status from './Status';

function App() {
    return (
        <Connector
          brokerUrl="mqtt://127.0.0.1:80/"
          parserMethod={(msg) => msg} // msg is Buffer
        >
          <Status />
        </Connector>
  );
}

export default App;

I get this error in the console

image

6 Answers

As mentioned in answers here please also consider the following:

npm install --save buffer

import {Buffer} from 'buffer';

It won't help in case of external library dependency but might save you from reverting other libraries in case of using Buffer in code directly.

I had this problem too.

Recently I create a new version of react app and when I used mqtt.js ( not mqtt-react-hooks ) this bad Error was shown!!!

I found out Webpack version 5 does not support Buffer and so on. Webpack 5 removes Buffer (see this info), effectively breaking MQTT library since it has explicit usages of it in the code.

so I downgrade to Webpack 4 and it's work. if you don't know how to do that, this link might be helpful. How to downgrade version of Webpack?.

To me downgrading react-scripts to version 4.0.3 fixed the problem. It is not a proper fix but its something...

In my case I needed to do the following also:

  1. In package.json use react-script 4.0.3
  2. Remove package-lock.json
  3. remove node_modules folder
  4. run npm install

After all this everything seems to be working fine.

In Webpack version 5, Webpack no longer automatically polyfill's Node.js API's if they are not natively supported anymore. The browser environment does not support Buffer natively, therefore we now need to add a third party Buffer package and point Node.js to it in the Webpack config. See how to polyfill buffer with webpack 5.

Use this on the page or function where you get an error:

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

for me what worked was:

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'
import inject from '@rollup/plugin-inject'

export default defineConfig({
    plugins: [vue()],
    resolve: {
        alias: {
            '@': path.resolve(__dirname, 'src'),
        }
    },
    build: {
        rollupOptions: {
            plugins: [inject({ Buffer: ['buffer', 'Buffer'] })],
        },
    },
})

reply to this comment:

https://github.com/vitejs/vite/discussions/2785#discussioncomment-1452855

Related