Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Uncaught ReferenceError: Buffer is not defined

Tags:

reactjs

mqtt

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

like image 700
Yehuda Zadik Avatar asked Mar 20 '26 18:03

Yehuda Zadik


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

like image 195
N Molchanov Avatar answered Mar 23 '26 07:03

N Molchanov


the only solution that worked for me was this:

npm add node-stdlib-browser
npm add -D vite-plugin-node-stdlib-browser

and then:

// vite.config.js
import { defineConfig } from 'vite'
import nodePolyfills from 'vite-plugin-node-stdlib-browser'

export default defineConfig({
  // other options
  plugins: [nodePolyfills()]
})
like image 23
Mariusz Avatar answered Mar 23 '26 06:03

Mariusz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!