How to Make an NFT in 14 Lines of Code

·

Creating your own Non-Fungible Token (NFT) might sound like a complex, high-barrier task reserved for elite blockchain developers. But the truth is, with modern development tools and open-source libraries, you can build and mint an NFT using just 14 lines of Solidity code. This guide walks you through the entire process—from setting up your development environment to deploying and minting your first NFT on the Ethereum test network.

Whether you're a beginner or an experienced developer diving into Web3, this tutorial is designed to be beginner-friendly while delivering real, deployable results.


What Is an NFT?

An NFT, or Non-Fungible Token, represents ownership of a unique digital asset on the blockchain. Unlike cryptocurrencies such as ETH or BTC, which are fungible (interchangeable), each NFT is one-of-a-kind.

As defined by Ethereum.org:

"NFTs are tokens that we can use to represent ownership of unique items. They let us tokenise things like art, collectibles, even real estate. They can only have one official owner at a time and they're secured by the Ethereum blockchain – no one can modify the record of ownership or copy/paste a new NFT into existence."

NFTs are secured by cryptography and stored immutably on the blockchain, making them ideal for digital art, virtual collectibles, in-game items, and more.


Understanding ERC-721: The NFT Standard

The most widely adopted standard for NFTs on Ethereum is ERC-721. This is a technical specification that defines how NFTs behave—ensuring compatibility across wallets, marketplaces, and applications.

ERC-721 outlines required functions like:

Thanks to open-source projects like OpenZeppelin, developers can inherit pre-audited, battle-tested implementations of ERC-721 without writing everything from scratch.

👉 Discover how blockchain developers turn ideas into deployable NFTs—start building now.


What Does "Minting" an NFT Mean?

Minting is the act of publishing a new NFT onto the blockchain. It involves:

  1. Deploying a smart contract
  2. Creating a unique token instance
  3. Assigning metadata (name, image, attributes)

Each NFT has a tokenURI—a link pointing to a JSON file containing metadata such as:

{
  "name": "Sad Circle",
  "description": "A sad circle.",
  "image": "https://i.imgur.com/Qkw9N0A.jpeg",
  "attributes": [
    { "trait_type": "Shape", "value": "Circle" },
    { "trait_type": "Mood", "value": "Sad" }
  ]
}

There are three ways to store this metadata:

For this tutorial, we'll use a custom API endpoint via Next.js for simplicity and rapid development.


Project Overview: Build & Mint Your First NFT

In this hands-on guide, you’ll:

No prior blockchain experience? No problem. We’ll use beginner-friendly tools like Hardhat, MetaMask, and Alchemy to simplify the process.

⚠️ This project is for learning purposes only and not intended for production use.

Prerequisites

1. MetaMask Wallet

You’ll need an Ethereum wallet to interact with the blockchain. MetaMask is a free browser extension and mobile app that manages your accounts and signs transactions.

2. Alchemy API Key

To communicate with the Ethereum network, you need access to a node. Running your own is complex—so we’ll use Alchemy, a reliable node-as-a-service platform.

3. Node.js & npm

Ensure you have Node.js installed (v14 or higher). You can verify with:

node -v
npm -v

If not installed, follow the guide at freeCodeCamp.


Initialize Your Project

Start by creating the project structure:

mkdir nft-project
cd nft-project
mkdir ethereum web

Inside ethereum/, set up Hardhat—a powerful Ethereum development environment:

cd ethereum
npm init -y
npm install --save-dev hardhat
npx hardhat

Choose "Create an empty hardhat.config.js".

Then, initialize a Next.js frontend in the web/ folder:

cd ../web
npx create-next-app@latest .

Your folder structure should now look like:

nft-project/
├── ethereum/
└── web/

Configure Environment Variables

Store sensitive data securely using .env:

cd ../ethereum
touch .env
npm install dotenv --save

Add your credentials to .env:

DEV_API_URL = https://eth-ropsten.alchemyapi.io/v2/YOUR_ALCHEMY_KEY
PRIVATE_KEY = YOUR_METAMASK_PRIVATE_KEY
PUBLIC_KEY = YOUR_METAMASK_ADDRESS

👉 Learn how top developers secure API keys and manage blockchain credentials safely.


Write the Smart Contract (14 Lines of Code)

Inside ethereum/contracts/, create EmotionalShapes.sol:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/utils/Counters.sol";

contract EmotionalShapes is ERC721 {
    using Counters for Counters.Counter;
    Counters.Counter private _tokenIdCounter;

    constructor() ERC721("EmotionalShapes", "ESS") {}

    function _baseURI() internal pure override returns (string memory) {
        return "https://your-ngrok-url/api/erc721/";
    }

    function mint(address to) public returns (uint256) {
        require(_tokenIdCounter.current() < 3);
        _tokenIdCounter.increment();
        _safeMint(to, _tokenIdCounter.current());
        return _tokenIdCounter.current();
    }
}

Breakdown:

Install OpenZeppelin:

npm install @openzeppelin/contracts

Build the Metadata API with Next.js

Navigate to web/pages/api/erc721/ and create [id].js:

const metadata = {
  1: {
    name: "Sad Circle",
    description: "A sad circle.",
    image: "https://i.imgur.com/Qkw9N0A.jpeg",
    attributes: [{ trait_type: "Shape", value: "Circle" }, { trait_type: "Mood", value: "Sad" }]
  },
  2: {
    name: "Angry Rectangle",
    description: "An angry rectangle.",
    image: "https://i.imgur.com/SMneO6k.jpeg",
    attributes: [{ trait_type: "Shape", value: "Rectangle" }, { trait_type: "Mood", value: "Angry" }]
  },
  3: {
    name: "Bored Triangle",
    description: "A bored triangle.",
    image: "https://i.imgur.com/hMVRFoJ.jpeg",
    attributes: [{ trait_type: "Shape", value: "Triangle" }, { trait_type: "Mood", value: "Bored" }]
  }
};

export default function handler(req, res) {
  res.status(200).json(metadata[req.query.id] || {});
}

Start the server:

cd ../web
npm run dev

Test it at http://localhost:3000/api/erc721/1.

Use ngrok to expose it publicly:

./ngrok http 3000

Update _baseURI() in your contract with the ngrok URL.


Deploy the NFT Contract

Install required packages:

npm install @nomiclabs/hardhat-ethers --save-dev

Update hardhat.config.js:

require("dotenv").config();
require("@nomiclabs/hardhat-ethers");

module.exports = {
  solidity: "0.8.0",
  defaultNetwork: "ropsten",
  networks: {
    ropsten: {
      url: process.env.DEV_API_URL,
      accounts: [`0x${process.env.PRIVATE_KEY}`],
    },
  },
};

Compile and deploy:

npx hardhat compile

Create scripts/deploy.js:

async function main() {
  const EmotionalShapes = await ethers.getContractFactory("EmotionalShapes");
  const emotionalShapes = await EmotionalShapes.deploy();
  console.log("Contract deployed at:", emotionalShapes.address);
}

main().catch(console.error);

Run:

node scripts/deploy.js

Mint Your NFT

Create scripts/mint.js:

require("dotenv").config();
const { ethers } = require("ethers");
const contract = require("../artifacts/contracts/EmotionalShapes.sol/EmotionalShapes.json");

const provider = ethers.getDefaultProvider("ropsten", { alchemy: process.env.DEV_API_URL });
const wallet = new ethers.Wallet(process.env.PRIVATE_KEY, provider);
const nftContract = new ethers.Contract("YOUR_CONTRACT_ADDRESS", contract.abi, wallet);

async function mint() {
  const tx = await nftContract.mint(process.env.PUBLIC_KEY);
  console.log("Minting transaction:", tx.hash);
}

mint();

Run:

node scripts/mint.js

Check the transaction on Ropsten Etherscan.

Add the NFT to MetaMask via the mobile app using your contract address and token ID.


Frequently Asked Questions (FAQ)

Q: Can I use this code on the main Ethereum network?

Yes—but replace Ropsten with Mainnet in your config and use real ETH. Be cautious with gas fees.

Q: Is storing metadata on Imgur safe?

No. For production, use IPFS or Arweave for permanent, decentralized storage.

Q: How do I sell my NFT after minting?

List it on marketplaces like OpenSea by connecting your wallet and uploading the contract address.

Q: Why use Hardhat instead of Truffle?

Hardhat offers better TypeScript support, built-in console.log debugging, and a modern plugin ecosystem.

Q: Can I mint more than 3 NFTs?

Yes—remove or increase the require(_tokenIdCounter.current() < 3); line in the contract.

Q: What are gas fees, and who pays them?

Gas fees compensate miners for processing transactions. The sender (you) pays them in ETH.


Final Thoughts

You’ve just built and minted an NFT using only 14 lines of Solidity code—a powerful demonstration of how accessible blockchain development has become.

With tools like Hardhat, OpenZeppelin, and Alchemy, creating digital assets is faster and safer than ever. Now that you understand the fundamentals, you can expand this project into a full marketplace, integrate wallets, or explore advanced features like royalties and lazy minting.

👉 Turn your NFT idea into reality—start building on Web3 today.


Core Keywords: NFT, ERC-721, smart contract, Solidity, blockchain development, minting NFT, Ethereum, Web3