Connecting metamask with backend in nodejs and express

i am trying to connect to MetaMask from backend but it’s not working. i have tried lot of libraries such as node-MetaMask, @metamask/detect-provider etc but unable to connect to MetaMask. please help

Hello @Sammed !)
Welcome to MetaMask community )

What specific error logs are you getting?
Make sure in your package.json that you have installed the latest version of the @metamask/detect-provider library (current version - 2.0.0).

3 Likes

Thank you for reply i am using latest version @metamask/detect-provider library and i am using detectprovider() function but after running that code it says window object is not defined. I am new to blockchain can u please provide code?? since i have less days remaining to submit my college project. below is my code

const detectEthereumProvider = require(‘@metamask/detect-provider’);
const { default: Wallet } = require(‘ethereumjs-wallet’);
const { default: Web3 } = require(‘web3’);

async function main() {
// Detect the MetaMask provider
const provider = await detectEthereumProvider();

if (provider) {
// Create a new Web3 instance using the provider
const web3 = new Web3(provider);

// Derive the private key from the user's mnemonic or private key (replace this with your own)
const mnemonic = 'test test test test test test test test test test test junk';
const path = "m/44'/60'/0'/0/0";
const wallet = Wallet.fromMnemonic(mnemonic, path);
const privateKey = wallet.getPrivateKeyString();

// Set the private key as the default account
web3.eth.accounts.wallet.add(privateKey);
web3.eth.defaultAccount = wallet.getAddressString();

// Test the connection by retrieving the user's default account balance
const balance = await web3.eth.getBalance(web3.eth.defaultAccount);
console.log('Default account:', web3.eth.defaultAccount);
console.log('Balance:', balance);

} else {
console.error(‘MetaMask not detected’);
}
}

main();

This library works on the client side, not the backend
Here is an example of a working connection, wrap your application with this provider and get the actual data from the context that is supplied by React out of the box:



import { createContext, useEffect, useState, useMemo } from "react";
import detectEthereumProvider from "@metamask/detect-provider";
import Web3 from "web3";


const Web3Context = createContext(null);

export default function Web3Provider({ children }) {
  const [Web3api, setWeb3api] = useState({
    provider: null,
    web3: null,
    isLoading: true,
    requireInstall: true,
  });

  const setListener = provider => {
    provider.on("chainChanged", _ => window.location.reload());
  };

  useEffect(() => {
    const loadProvider = async () => {
      const provider = await detectEthereumProvider();

      if (provider) {
        const web3 = new Web3(provider);
        setListener(provider);

        setWeb3api({
          provider,
          web3,
          isLoading: false,
          requireInstall: false
        });
      } else {
        setWeb3api(prev => ({
          ...prev,
          isLoading: false
        }));

        console.error("gotta be install metamask");
      }
    };
    loadProvider();
  }, []);

  const _web3Api = useMemo(() => {
    return {
      ...Web3api,
      connect: Web3api.provider
        ? async () => {
            try {
              await Web3api.provider.request({
                method: "eth_requestAccounts"
              });
            } catch {
              console.error("cannot access to account");
              window.location.reload();
            }
          }
        : () => {
            console.error(" cannot connect to MetaMask ");
          },
      requireInstall: !Web3api.isLoading && !Web3api.web3
    };
  }, [Web3api]);

  return (
    <Web3Context.Provider value={_web3Api}>{children}</Web3Context.Provider>
  );
}

export function useWeb3() {
  return useContext(Web3Context);
}
1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.