Uncaught ReferenceError: Buffer is not defined in React
Asked Answered
S

7

33

If I add the following lines into my code it throws the following error:

import { BIP32Interface } from "bip32";

let node: BIP32Interface = bip32.fromBase58(key);

Error:

Uncaught ReferenceError: Buffer is not defined

I'm using the same package in a Next.js app, so I think the problem here, that I haven't got node.js environment when compiling happens...

How could I pass this issue?

I tried: yarn add buffer ->

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

Any ideas?

Sempiternal answered 2/6, 2021 at 11:15 Comment(0)
C
51

Install the browser buffer package:

npm install --save buffer

Import it and use it directly, example:

import {Buffer} from 'buffer';
Buffer.from('anything','base64');
Constance answered 14/7, 2021 at 14:33 Comment(2)
why --save is needed?Fluvial
It is not. It used to be, it would save the package to you package.json I believe. Now it's automaticYellowbird
I
15

First do this:

npm install --save buffer

Then add

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

after my import statements. It worked for me.

Indene answered 17/4, 2022 at 19:35 Comment(2)
Would you mind adding WHY this works?Delirium
This works as the problem is that window.Buffer is undefined unless defined by some plugin, this sets the buffer to the buffer library that you installed. For typescript this worked for me: import { Buffer } from 'buffer'; if (!window.Buffer) { window.Buffer = Buffer; } Lorola
M
9

I got this buffer error when I tried to upload object (doc/pdf/image) etc from react to AWS S3 Bucket. Then after referring multiple website i got the solution below.

Find this sample react code to understand.

import logo from './logo.svg';
import './App.css';
import S3FileUpload from 'react-s3';
window.Buffer = window.Buffer || require("buffer").Buffer;

function App() {
  const onFileChange = (file)=>{
    const config = {
      bucketName: 'bucket-name',
      dirName: 'photos', /* optional */
      region: 'us-east-1',
      accessKeyId: 'access-key-id',
      secretAccessKey: 'secret-access-key',
    }
    S3FileUpload.uploadFile(file, config)
    .then((data)=>{
      console.log(data.location);
    }).catch((err)=>{
      alert(err);
    })
  }

  return (
    <div className="App">
      <h1>Hello React</h1>
      <input type="file" onChange={(e)=>onFileChange(e.target.files[0])} />
    </div>
  );
}

export default App;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

window.Buffer = window.Buffer || require("buffer").Buffer; Add this statement after all the import statements to get rid of "buffer is not defined"

Mendelism answered 31/3, 2022 at 9:59 Comment(0)
B
6

I was getting the same error and this is how I solved the problem. But I have no clue as to why.

firs:

npm install --save buffer

(I don't know what it does, but it worked.) and then;

import { Buffer } from "buffer";

Buffer.from("anything", "base64");
window.Buffer = window.Buffer || require("buffer").Buffer;
Beaded answered 15/5, 2022 at 15:43 Comment(1)
This worked for me on VUE 3 CLI projectBoyfriend
B
2

for me what worked was:

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

export default defineConfig({
    plugins: [react()],
    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

Biolysis answered 30/6, 2022 at 22:51 Comment(0)
S
1

i am using vite + react and can work below

import { NodeGlobalsPolyfillPlugin } from '@esbuild-plugins/node-globals-polyfill'
export default defineConfig({
    // ...other config settings
    optimizeDeps: {
        esbuildOptions: {
            // Node.js global to browser globalThis
            define: {
                global: 'globalThis'
            },
            // Enable esbuild polyfill plugins
            plugins: [
                NodeGlobalsPolyfillPlugin({
                    buffer: true
                })
            ]
        }
    }

})

in vite.config.ts, check here Buffer is not defined in React-vite

Symptomatology answered 14/12, 2023 at 4:1 Comment(0)
E
0

Install the browser buffer package:

npm install --save buffer

Then use this in your component

 import { Buffer } from "buffer/"; 
 window.Buffer = Buffer;

This worked for me(Vite-Project)

Emissive answered 10/10, 2023 at 6:18 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.