Set up the x402 facilitator

Before you can build endpoints for premium research feeds, you need a facilitator. This component acts as the middleware between your API and the payment network. It handles the initial handshake, validates the transaction, and ensures that the buyer has paid before your server returns the requested data.

The Coinbase Developer Platform provides the most robust implementation for this protocol. Their official quickstart guide walks you through the integration process for sellers, ensuring your API can charge buyers and AI agents effectively 1. While other implementations exist, starting with the Coinbase facilitator reduces the complexity of handling Base network transactions.

x402 Endpoints for Premium Research Feeds
1
Install the facilitator package

Begin by adding the facilitator SDK to your project. This package contains the necessary libraries to intercept HTTP requests and manage the payment state. Run the installation command in your terminal to pull the dependencies into your development environment.

x402 Endpoints for Premium Research Feeds
2
Configure environment variables

Next, create a .env file to store your private keys and wallet addresses. Never hardcode these values in your source code. The facilitator needs these credentials to sign transactions on the Base network. Keep these keys secure, as they control the funds associated with your research feeds.

to x402 Endpoints for Premium Research Feeds
3
Initialize the middleware

Import the facilitator into your main server file. Initialize it with your configuration object, passing in the environment variables you just set. This step registers the payment handler with your HTTP server, allowing it to listen for the specific x402 headers that signal a completed payment.

Once the facilitator is initialized, your API is ready to receive payment requests. The middleware will automatically pause the response until the payment is confirmed on-chain. This setup ensures that only users who have paid for access can retrieve the premium research data you are selling.

Return HTTP 402 with Payment Instructions

When an unauthenticated or unpaid request hits your premium research endpoint, the standard behavior is to return an HTTP 402 status code. This signal tells the client that payment is required to access the content. Unlike a 401 (Unauthorized) or 403 (Forbidden), a 402 response is specifically designed for commercial transactions, making it the correct choice for x402 endpoints.

The response must include a valid payment payload. This payload contains the instructions for the client to complete the transaction, typically using USDC on a supported network like Base. The client uses these instructions to route the payment before retrying the request. Without this structured payload, automated agents cannot process the payment, and the transaction fails.

Step 1: Detect the Unpaid Request

Check the request headers for valid payment credentials or tokens. If the request lacks authentication or the token is invalid, trigger the payment flow.

JavaScript
if (!request.headers.authorization) {
  return handlePaymentRequired(request);
}

Step 2: Construct the 402 Response

Build the response body with the payment details. Include the token amount, currency (USDC), and the recipient address. This data is what the client’s agent will read to initiate the transfer.

JavaScript
const response = {
  status: 402,
  body: {
    amount: "0.01",
    currency: "USDC",
    chainId: 8453,
    recipient: "0xYourWalletAddress"
  }
};

Step 3: Include Routing Instructions

Add clear routing instructions to the payload. This ensures the client knows exactly where to send the funds. For x402, this often involves a smart contract interface or a direct wallet transfer method. The client must be able to parse this instruction to complete the payment.

1
Detect Unpaid Requests

Check headers for payment credentials. If missing, trigger the payment flow.

2
Construct 402 Response

Build the response with amount, currency, and recipient details.

3
Include Routing Instructions

Add clear instructions for the client to route the payment correctly.

By following this sequence, you ensure that your endpoint behaves correctly according to the x402 standard. The client receives a clear signal and the data needed to pay, allowing the interaction to proceed smoothly once the transaction is confirmed.

Verify payment proof on subsequent requests

Once a client has paid for access, they receive a signed x-payment-proof header. On every subsequent request, your endpoint must validate this proof before serving the premium research data. This step prevents unauthorized access and ensures that only paying users can retrieve the feed.

The verification process involves checking the cryptographic signature against the blockchain or a trusted facilitator. You need to confirm that the payment was legitimate, that the signature hasn't expired, and that the amount matches the required fee for the specific dataset.

1. Extract and parse the proof header

Start by extracting the x-payment-proof header from the incoming request. This header contains a JSON Web Signature (JWS) or similar cryptographic payload. Parse this payload to retrieve the embedded claims, which typically include the transaction hash, the amount paid, the timestamp, and the sender's public key.

2. Validate the cryptographic signature

Use your preferred cryptographic library to verify the signature against the known public key or the blockchain state. This step ensures that the proof was genuinely created by the payer and hasn't been tampered with. If the signature verification fails, reject the request immediately with an 401 Unauthorized status.

3. Check expiration and amount

Even a valid signature can be stale. Check the exp (expiration) claim in the proof to ensure the payment is still active. Also, verify that the amount field matches the price of the specific research feed being requested. If the amount is insufficient or the proof has expired, deny access.

4. Record and serve data

If all checks pass, log the valid proof for audit purposes and serve the premium research data. You can now treat the request as authenticated. For subsequent requests with the same valid proof, you can skip heavy blockchain lookups if your protocol allows cached validity windows, but always re-verify the signature structure.

x402 Endpoints for Premium Research Feeds
1
Extract the header

Parse the x-payment-proof header from the HTTP request to isolate the cryptographic payload.

2
Verify the signature

Validate the JWS signature against the public key or blockchain state to ensure authenticity.

3
Check validity

Confirm the payment amount matches the feed price and the proof has not expired.

4
Serve the data

Log the valid proof and return the premium research data to the client.

Handle payment expiry and refresh logic

When building x402 endpoints for premium research feeds, the session lifecycle is just as important as the initial payment. A token that worked yesterday may not work today, so your system needs a clear plan for when access expires. Without this logic, your API either loses revenue by letting free access linger or frustrates legitimate users by locking them out unexpectedly.

1. Return 402 with Expiry Headers

When a client’s payment token has expired or lacks sufficient funds, your endpoint must return a 402 Payment Required status. This is the core of the x402 protocol. Along with the status code, include headers that specify the exact payment amount and currency. This signals to the client that the service is available but requires a fresh transaction to continue.

2. Implement Token Refresh Logic

Clients need a way to renew their access without starting from scratch. Design your API to accept a refresh token or a new payment signature that updates the user's session state. When the client presents a new valid payment proof, update the expiration timestamp in your database. This ensures seamless continuity for the researcher while maintaining strict payment boundaries.

3. Re-verify Session on Each Request

For high-stakes financial data, never assume a session is still valid based on local cache. Verify the payment status on every incoming request. If the token is expired, revoke access immediately and return the 402 response. This prevents "zombie sessions" where users continue to consume premium data after their payment has lapsed.

4. Notify Clients Before Expiry

To reduce support tickets and user churn, implement a grace period. Your API can return a 423 Locked or a custom header warning clients that their token will expire soon. This gives the client’s automation logic time to fetch a new payment token before the session actually dies, ensuring uninterrupted data flow.

5. Log and Audit Payment Events

Keep a detailed log of all payment successes, failures, and expirations. These logs are critical for debugging why a premium user might have been locked out unexpectedly. They also provide the audit trail necessary for financial reconciliation, ensuring that every byte of data served was properly paid for.

Common mistakes in x402 implementation

Even with a solid architecture, small oversights in how you handle payment proofs can break the security model of your premium research feed. The most frequent error is trusting client-side signals. If your endpoint returns data based solely on a browser-reported status, you have effectively left the vault door open.

Always verify the payment proof on the server side. Treat the client’s claim of payment as untrusted input. You must validate the actual transaction hash or facilitator receipt against your backend logic before serving any sensitive data. This is non-negotiable for high-stakes financial information.

Another critical pitfall is ignoring network latency. Payment proofs can take time to propagate, especially on slower chains. If your server rejects a valid proof because it arrived slightly late, you will frustrate legitimate users and lose revenue. Implement a short, configurable retry window or a status-check endpoint that allows the client to confirm the proof has been indexed before expecting the full data payload.

Finally, ensure your error handling is precise. A generic "500 Internal Server Error" gives attackers no clues about what went wrong, but it also makes debugging difficult for your own team. Return specific 402 or 403 errors with clear messages when a proof is invalid or missing, so developers integrating your feed can adjust their request logic immediately.

Frequently asked questions about x402

What is x402?

x402 is an open, internet-native payment protocol built on top of the standard HTTP 402 status code. Developed by the Coinbase Development Platform team, it allows APIs and web services to require payment before serving data or content. Instead of relying on traditional subscription models or manual invoicing, x402 embeds payment verification directly into the web protocol. Learn more about the protocol on docs.x402.org.

How does the x402 protocol work?

The protocol operates by returning a 402 Payment Required status code when a request lacks payment. This response includes a specific payload detailing the required amount and the destination wallet address. Once the user or AI agent sends the stablecoin payment, the server verifies the transaction on-chain and returns the requested data. This creates a seamless, automated transaction loop without needing user accounts or human approval. See how x402 enables agent commerce.

How to buy Coinbase x402?

If you are looking to acquire x402 tokens for trading or integration testing, you can purchase them through major exchanges. Start by creating a Coinbase account and funding it with a debit card or bank transfer. Search for "x402" in the app, then initiate a trade. You can buy directly or use a Decentralized Exchange (DEX) if you are holding funds in a compatible wallet. Follow the full buying guide on Coinbase.

What are the different use cases for the x402 protocol?

x402 is primarily designed for machine-to-machine (M2M) commerce, particularly for AI agents that need to access premium data feeds. Common use cases include pay-per-query API endpoints for financial research, premium news archives, and specialized datasets. It also supports microtransactions for web content, allowing developers to monetize specific resources without requiring users to sign up for long-term subscriptions.