Why NFT metadata needs paid refresh

NFT metadata is the descriptive information that tells software what an NFT is supposed to represent. Without it, an NFT is just a token contract address and a unique ID on a ledger—a digital skeleton without a body. To function as a picture, a game item, or a dynamic character, it needs that descriptive layer.

For dynamic NFTs, this metadata isn't static. It changes based on real-world events, game progress, or external data feeds. This creates a natural economic friction: updating that data requires server resources, API calls, and storage. If you offer these updates for free, you risk being drained by automated bots or simply unsustainable traffic. Charging for each refresh turns your endpoint into a sustainable service rather than a public utility you're forced to maintain.

This is where x402 changes the game. Instead of building complex user accounts, login systems, or payment gateways, you can embed the payment directly into the API request. The x402 facilitator acts as the middleman, verifying that the buyer has sent the payment before your API returns the updated metadata. This turns every metadata update into a simple, trustless transaction.

The result is a self-funding system. Every time an NFT's state changes, the user pays for that change. This aligns the incentives: you get compensated for the compute power required to keep the NFT alive and relevant, and the user gets immediate, verified access to the latest data. It’s not just about protecting your server; it’s about creating a micro-economy around your digital assets.

Set up the x402 facilitator

Before your API can return updated NFT metadata, you need a way to verify that the buyer has actually paid. Thirdweb's x402 facilitator handles the payment verification so your endpoint doesn't have to manage complex crypto logic directly. Think of it as a bouncer at the club door: it checks the wallet, confirms the USDC transfer, and only then lets the request through to your code.

We will use the official Thirdweb SDK to install and configure this facilitator. This setup ensures that your metadata refresh endpoint is secure and only accessible to those who have completed the transaction.

1
Install the Thirdweb SDK

Start by adding the necessary dependencies to your project. If you are using npm, run the following command in your terminal to install the core SDK and the x402 facilitator package:

Shell
Shell
npm install @thirdweb-dev/sdk @thirdweb-dev/facilitator

This installs the libraries required to interact with the blockchain and handle the x402 protocol. Ensure your project is initialized as an ES module or configured to handle the imports correctly.

2
Initialize the Facilitator

Create a new file for your facilitator configuration, such as facilitator.ts. Import the createFacilitator function from the SDK. You will need to pass your Thirdweb client ID and the specific chain ID where your NFT contract resides (e.g., 84532 for Base Sepolia or 8453 for Base Mainnet).

TypeScript
TypeScript
import { createFacilitator } from "@thirdweb-dev/facilitator";

const facilitator = createFacilitator({
  clientId: "YOUR_THIRDWEB_CLIENT_ID",
  chainId: 84532,
});

This instance will be used to verify payments in subsequent steps. Keep your client ID secure and never expose it in client-side code.

3
Configure Payment Verification

Your x402 endpoint needs to know what payment to expect. Define the expected token (usually USDC) and the amount. The facilitator will check the buyer's wallet for this specific transfer before allowing access to your metadata.

TypeScript
TypeScript
const paymentConfig = {
  token: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", // USDC on Base
  amount: "1000000", // 1 USDC (6 decimals)
};

Pass this configuration to your endpoint handler. The facilitator will intercept the request, verify the transaction on-chain, and reject any requests that do not meet these criteria.

4
Test the Integration

Before deploying, test the flow locally. Use a wallet with sufficient USDC balance to make a test payment. Verify that the facilitator correctly identifies the transaction and returns a success status. If the payment is missing or incorrect, the facilitator should return a 402 Payment Required error.

This step ensures that your metadata refresh logic only triggers after successful payment, maintaining the integrity of your x402 endpoint.

Connect to NFT metadata APIs

Once your x402 endpoint is ready to handle payments, you need a way to actually update the NFT's on-chain or off-chain data. This section covers how to connect to the major metadata providers—OpenSea, Alchemy, and custom IPFS storage—to trigger a refresh.

Think of this step as handing your x402 endpoint a key to the NFT's locker. The endpoint collects the payment, but the API integration is what physically turns the lock and updates the record. Without this connection, the payment goes nowhere and the metadata stays stale.

1. Authenticate with your provider

Before you can send a refresh request, you need credentials. OpenSea and Alchemy both require API keys.

  • OpenSea: Generate an API key from your OpenSea dashboard. You will need this to sign requests or pass as a header.
  • Alchemy: Create a new app in the Alchemy dashboard to get your API key. Ensure you are targeting the correct network (e.g., Ethereum Mainnet).
  • IPFS: If you are using a custom gateway like Pinata or Infura, generate an API key with write permissions.

Keep these keys secure. Never expose them in client-side code or public repositories. Use environment variables to store them in your x402 server.

2. Construct the refresh request

Each provider has a specific endpoint for refreshing metadata. You will need to send a POST request to this endpoint with the correct payload.

  • OpenSea: Use the Refresh NFT Metadata endpoint. You need the contract address, token ID, and the token standard (ERC-721 or ERC-1155). OpenSea will re-fetch the metadata from the source URI.
  • Alchemy: Use the Refresh NFT Metadata endpoint. This is supported on Ethereum Mainnet and Polygon. The payload requires the contract address and token ID.
  • IPFS: If you are storing metadata on IPFS, you typically update the JSON file itself, then re-pin it. Some gateways allow you to trigger a refresh by re-uploading the same content, but often you just need to ensure the pin is active.

3. Handle the response

API refreshes are often asynchronous. The endpoint might return a 200 OK with a request ID, indicating that the refresh is queued. You should not assume the metadata is updated immediately.

  • Check status: If the provider offers a status endpoint, poll it to confirm the refresh is complete.
  • Fallback: If the refresh fails, log the error and alert the user. Do not mark the x402 transaction as complete until you have confirmation that the metadata update was successful.
  • Timeouts: Set reasonable timeouts. If the API hangs, retry once, then fail gracefully.

4. Verify the update

After the refresh, verify that the metadata has changed. You can do this by fetching the metadata directly from the provider or by checking the token URI on-chain.

  • OpenSea: Visit the NFT page on OpenSea and check if the image or attributes have updated.
  • Alchemy: Use the getNFTMetadata endpoint to fetch the latest data and compare it to your expected values.
  • IPFS: Use an IPFS gateway to fetch the JSON file and check the timestamp or content hash.

If the metadata is not updated, check the provider's logs for errors. Common issues include incorrect contract addresses, token IDs, or network mismatches.

5. Secure the integration

Since your x402 endpoint is handling payments, the metadata refresh is a critical part of the value delivery. Ensure that:

  • Rate limiting: Implement rate limiting on your API calls to avoid hitting provider limits.
  • Error handling: Wrap API calls in try-catch blocks to handle network errors gracefully.
  • Logging: Log all refresh attempts, including success and failure, for auditing and debugging.

By following these steps, you ensure that your x402 endpoint not only collects payment but also delivers the promised NFT metadata update reliably.

Handle payment verification logic

Once the client sends the request, your server needs to confirm the payment actually happened before you reveal the updated metadata. You don’t need to build a complex blockchain explorer from scratch. Thirdweb’s x402 facilitator handles the verification, checking that the buyer has sent the payment before your API returns the updated metadata.

The verification process follows a strict sequence. First, extract the x402-payment header from the incoming HTTP request. This header contains the signed transaction details. Next, pass this header to the Thirdweb verification utility. The utility checks the transaction against the blockchain to ensure it matches the expected amount and token.

If the payment is valid, the request proceeds. If it fails, you return a 402 Payment Required error immediately. Do not expose any metadata in the error response. This prevents attackers from scraping your data by simply testing different endpoints.

TypeScript
import { verifyX402Payment } from '@thirdweb-dev/x402';

export async function GET(request: Request) {
  const paymentHeader = request.headers.get('x402-payment');
  
  if (!paymentHeader) {
    return new Response('Payment required', { status: 402 });
  }

  const isValid = await verifyX402Payment({
    payment: paymentHeader,
    amount: '1000000', // 1 USDC in wei
    token: '0x...', // USDC contract address
  });

  if (!isValid) {
    return new Response('Invalid payment', { status: 402 });
  }

  // Return updated metadata
  return new Response(JSON.stringify({ name: 'Updated NFT' }));
}

Test your endpoint with real transactions

Before you push this to mainnet, you need to verify that the x402 facilitator correctly gates access. The facilitator ensures the buyer has sent the payment before your API returns the updated metadata. If this handshake fails, your NFTs won't update, and users will see stale data.

Run through this pre-launch checklist on a testnet like Sepolia or Mumbai. These environments let you simulate transactions without risking real capital.

  • Deploy the smart contract to a testnet.
  • Send a test payment (e.g., 0.001 ETH) from a test wallet.
  • Verify the facilitator acknowledges the payment.
  • Confirm your API returns the new metadata payload.
  • Check that the NFT token URI updates in the explorer.

If any step fails, check your event listeners and gas settings. Once all items are checked, you are ready to deploy.

Frequently asked questions about x402

These answers address the most common developer questions regarding x402 implementation and NFT metadata refreshes.