How to create a NFT mint website using web3

In this tutorial we are going to build a NFT mint website using web3 considering that you already have the contract deployed on the blockchain.

In this tutorial we are going to build a NFT mint website using web3 considering that you already have the contract deployed on the blockchain.

The first step is to install web3 if you haven't already:

npm install web3

Then, to interact with a blockchain (Ethereum or BSC or any other) you need to create an instance of Web3 and give it a provider (like window.ethereum for browser wallets, for example).

After that, you need to connect to the user's wallet using any method you want. You can check out our guides if you want to learn how to connect to a wallet.

Next, you need to find the contract method that will mint the NFT and create an ABI containing that method.

If the contract is not yours, find it in etherscan.io (for contracts in the ETH blockchain) and find that method under the "Write contract" section. Usually it's a method containing "mint" or "purchase" or something similar in the name and it has 2 parameters, one for the number of NFTs to mint and the other with the payable amount in ether.

Now, you need to instantiate your contract using your ABI.

// need a Web3 instance initialized with a provider like window.ethereum for browser wallets, in a variable called web3, to use this code stored
// also need a connected wallet using that instance

const contractAddress = "0x81c587EB0fE773404c42c1d2666b5f557C470eED"
const contract = new web3.eth.Contract(ABI, contractAddress)

Now you create a transaction using the token URI that you can find on the contract information or you should have it if it's your contract. You can also have it from your metadata if you are using a storage system like pinata:

const fromAddress = "0x...." // your address
const tx = {
  'from': fromAddress,
  'to': contractAddress,
  // if you need to pay for the mint, add the amount (as a string):
  'value': Web3.utils.toHex(Web3.utils.toWei(amount, 'ether'))
  'data': contract.methods.mintNFT(fromAddress, tokenURI).encodeABI()
};

Using these parameters, you can now send the transaction:

const txHash = await web3.eth.sendTransaction(tx);

Then you can also handle errors on this request or handle a user's rejection if you wrap it around a try...catch block or use promises with .then and .catch.

The code is very similar to the code you use to send an ERC-20 token to another user. If you don't know how to do it, check our here how to send an ERC-20 token with web3.

Thanks for reading this article!