Nextjs 13.0.2 and Ethers why is my Provider undefined?
Asked Answered
C

2

7

I'm trying to access the ethers provider like this in Nextjs 13.0.1:

import { ethers } from "ethers";

export const signMessage = () => {
  
  const provider = new ethers.providers.Web3Provider(window.ethereum);
  const signer = provider.getSigner();

  try {
    signer.signMessage("Hey hey").then((result) => {
      console.log(result);
    });
  } catch (error) {
    // handle error
    console.log(error);
  }
};

But it always gives me the error:

Unhandled Runtime Error
TypeError: Cannot read properties of undefined (reading 'Web3Provider')

I've tried different providers but always get the error message above.

Someone knows why it's working for Nextjs 12 but not for Next 13?

Commitment answered 5/2, 2023 at 11:6 Comment(0)
A
7

I think you are using version 6 in next13. if you install

"ethers": "^5.6.4",

in next-13, it will work.

I think you previously had next-12 project with version 5, and now installing new version on next-13

in ethers v6 all of those

export {
    getDefaultProvider,
    Block, FeeData, Log, TransactionReceipt, TransactionResponse,
    AbstractSigner, NonceManager, VoidSigner,
    AbstractProvider,
    FallbackProvider,
    JsonRpcApiProvider, JsonRpcProvider, JsonRpcSigner,

    BrowserProvider,
    AlchemyProvider, AnkrProvider, CloudflareProvider, EtherscanProvider,
    InfuraProvider, PocketProvider, QuickNodeProvider,
    IpcSocketProvider, SocketProvider, WebSocketProvider,
    EnsResolver,
    Network
} from "./providers/index.js";

are imported like this

import { BrowserProvider } from "ethers";

const providerr = new BrowserProvider(window.ethereum);

this is how I set a component to connect

const Test = () => {
  const [provider, setProvider] = useState();
  useEffect(() => {
    const browserProvider = new BrowserProvider(window.ethereum);
    setProvider(browserProvider);
  }, []);
  const connect = async () => {
    await provider.send("eth_requestAccounts");
  };
  return (
    <div>
      <button onClick={connect}>connect</button>
    </div>
  );
};

export default Test;
Amphistylar answered 5/2, 2023 at 16:3 Comment(1)
OMG!!! I was trying to debug the entire day... you're a day safer! Thank you so much!Commitment
E
1

If you are using "ethers": "^6.0.2" like me then use this :

const web3Provider = new ethers.BrowserProvider(window.ethereum);

Also then getting signer you should remember that web3Provider.getSigner() will return a promise so use await or then

const signer = await web3Provider.getSigner();

Check more on ethers documentation

Emissive answered 16/2, 2023 at 19:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.