Trouble fetching NFT metadata in Solidity contract

I’m working on an NFT project and testing it on the Ropsten network. My metadata files are stored on my website, but I’m running into a problem. The contract is trying to access the metadata without the .json extension.

For instance, if I have a file at myNFTsite.com/metadata/5.json, the contract is looking at myNFTsite.com/metadata/5 instead. This is causing issues with loading the correct metadata.

Here’s the current function in my Solidity contract:

function _baseURI() internal pure override returns (string memory) {
    return "https://myNFTsite.com/metadata/";
}

How can I modify this to make sure it includes the .json extension when fetching metadata? Any help would be appreciated!

hey there creativePainter45! that’s an interesting issue you’re running into with your nft metadata. have you considered modifying your _baseURI function to include the .json extension? something like this might work:

function _baseURI() internal pure override returns (string memory) {
    return "https://myNFTsite.com/metadata/";
}

function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
    return string(abi.encodePacked(super.tokenURI(tokenId), ".json"));
}

this way, you’re appending the .json to each token URI. what do you think? have you tried something similar? i’m curious to hear if this solves your problem or if you’ve found another workaround. let me know how it goes!

I encountered a similar issue with my NFT project. One solution that worked for me was modifying the tokenURI function instead of _baseURI. Here’s what I implemented:

function tokenURI(uint256 tokenId) public view override returns (string memory) {
    return string(abi.encodePacked(
        _baseURI(),
        Strings.toString(tokenId),
        '.json'
    ));
}

This approach concatenates the base URI, token ID, and .json extension. It ensures each token’s metadata is fetched correctly without altering the base URI. Remember to import the Strings library if you haven’t already.

Have you considered this method? It’s been reliable in my experience, but I’m curious if you’ve tried other approaches or if there are specific constraints in your project that might affect this solution.

yo creativePainter45, had same issue b4. try this:

function tokenURI(uint256 tokenId) public view override returns (string memory) {
    return string(abi.encodePacked(_baseURI(), Strings.toString(tokenId), '.json'));
}

adds .json to each URI. works like charm for me. lmk if it helps!