'React Uncaught ReferenceError: Buffer is not defined

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



Solution 1:[1]

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.

Solution 2:[2]

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?.

Solution 3:[3]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 N Molchanov
Solution 2
Solution 3 Iván