I am trying to add this code to handle the change of accounts in Metamask...

  .request({ method: 'eth_accounts' })
  .catch((err: any) => {
    // Some unexpected error.
    // For backwards compatibility reasons, if no accounts are available,
    // eth_accounts will return an empty array.

  if (ethereum) {
    // running on client and window + ethereum is avail
  } else {
    // you are on the server.
    // OR user does not have a broswer wallet - i.e. metamask
// Note that this event is emitted on page load.
// If the array of accounts is non-empty, you're already
// connected.
ethereum.on('accountsChanged', handleAccountsChanged);

...but I am getting the following error in my TypeScript project:

TypeError: Cannot read properties of null (reading 'request')

ethereum has been defined like this, using metamask-react:

  const { status, connect, account, chainId, ethereum } = useMetaMask();

It seems that the object ethereum is not being correctly loaded.

Any thoughts?

2 Answers 2


although npm page says ts support but type for ethereum is any in the source code.

export declare function useConnectedMetaMask(): {
    account: string;
    chainId: string;
    status: "connected";
} & {
    connect: () => Promise<string[] | null>;
    addChain: (parameters: import("./metamask-context").AddEthereumChainParameter) => Promise<void>;
    switchChain: (chainId: string) => Promise<void>;
    ethereum: any;

I posted the proper type for Ethereum in this StackOverflow post.

Initially, I had the same error, the request was not sending to pop up the metamask window. It was because I was already connected to the metamask at localhost:3000 from my other apps. So I manually disconnected and set useEffect

 const { status, connect, account, chainId, ethereum } = useMetaMask();

useEffect(() => {
    ethereum?.request({ method: "eth_requestAccounts" });

  }, []);

when page was loading, I get metamask window pop-up.



import { ExternalProvider } from '@ethersproject/providers';

 declare global {
   interface Window {
     ethereum?: ExternalProvider

On your app.tsx and call ethereum object as window.ethereum. The object will be only avaiable if there's any metamask account logged so you need to verify:

console.log('no ethereum wallet connected')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.