2

I am upgrading to Webpack 5 and I have an issue with the package jsonwebtoken (https://github.com/auth0/node-jsonwebtoken) that needs Buffer (at https://github.com/auth0/node-jsonwebtoken/blob/master/sign.js#L91) Since Webpack 5 polyfills are not included for nodejs functions and wen I try to use the function sign from jsonwebtoken it throws the following error :

message: "Buffer is not defined"
stack: "ReferenceError: Buffer is not defined↵    
at module.exports (webpack-internal:///./node_modules/jsonwebtoken/sign.js:91:26)↵ 

To solve the issue I installed https://github.com/feross/buffer with

npm install buffer

and in my webpack config I added

 resolve: {
    fallback: {
      "Buffer": require.resolve('buffer/'),
    }

or

 resolve: {
    fallback: {
      "buffer": require.resolve('buffer/'),
    }

I also tried

 resolve: {
    fallback: {
      "buffer": require.resolve('buffer/').Buffer,
    }

But this last one produce a Webpack schema error :

 configuration.resolve.fallback['Buffer'] should be one of these:
      [non-empty string, ...] | false | non-empty string
      -> New request.
      Details:
       * configuration.resolve.fallback['Buffer'] should be an array:
         [non-empty string, ...]
         -> Multiple alternative requests.
       * configuration.resolve.fallback['Buffer'] should be false.
         -> Ignore request (replace with empty module).
       * configuration.resolve.fallback['Buffer'] should be a non-empty string.
         -> New request.
    at validate (/home/ant1/packcity/front-pmd/node_modules/webpack/node_modules/schema-utils/dist/validate.js:104:11)

Despite my trials it is not working and the error persists.

Did someone succeed in adding the polyfill for Buffer in their app bundled with Webpack ? Any help would be really appreciated.

Ant1
  • 344
  • 5
  • 12

3 Answers3

4

I just solved my issue by adding

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

As suggested here https://github.com/ipfs/js-ipfs/issues/3369#issuecomment-721975183

Ant1
  • 344
  • 5
  • 12
1

I found this question when having a similar issue with Gatsby. To fix, I added:

exports.onCreateWebpackConfig = ({ actions }) => {
    actions.setWebpackConfig({
        plugins: [
            new webpack.ProvidePlugin({
                Buffer: [require.resolve("buffer/"), "Buffer"],
            }),
        ]
    }
}

to my gatsby-node.js config.

eth0
  • 4,977
  • 3
  • 34
  • 48
1

I have solved it this way in Gatsby. I didn't have to install the buffer dependency. Just added this to my gatsby-node.js file.

exports.onCreateWebpackConfig = ({ actions, stage, plugins }) => {
    if (stage === 'build-javascript' || stage === 'develop') {
        actions.setWebpackConfig({
            plugins: [plugins.provide({ Buffer: ['buffer/', 'Buffer'] })]
        });
    }
};