'NEAR protocol ReferenceError: Buffer is not defined

I'm getting ReferenceError: Buffer is not defined when trying to use near-api-js.

The relevant lines of code are:

export const near = new Near({
  networkId,
  keyStore: new keyStores.BrowserLocalStorageKeyStore(),
  nodeUrl,
  walletUrl,
  headers: null,
});

export const walletConnection = new WalletConnection(near, appKeyPrefix);

walletConnection.requestSignIn({ // This line causes the problem
    contractId,
    methodNames: [],
});

My project is a fresh installation of Gatsby.

Any ideas what I'm missing?



Solution 1:[1]

I ran yarn add buffer.

Then I prepended my file with these lines:

import * as buffer from 'buffer';
(window as any).Buffer = buffer.Buffer; // https://github.com/isaacs/core-util-is/issues/27#issuecomment-878969583

See https://github.com/isaacs/core-util-is/issues/27#issuecomment-878969583

Then it seemed to work.

But this feels like a weird hack, and I didn't expect to need to do something like this. But I couldn't find any better way in any NEAR docs. I'm curious what other people will suggest here.

Solution 2:[2]

This is pending issue in near-api-js, check here for more details, https://github.com/near/near-api-js/issues/757.

Might be resolve soon.

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 Ryan
Solution 2 masterhunter