Set up x402 payment middleware

Before you can route KYC or AML checks through an x402-enabled API, you need to install the necessary dependencies and configure the payment facilitator. This middleware acts as the gatekeeper, ensuring that a valid USDC payment is settled before your backend processes any sensitive identity data.

We will use the official Coinbase Developer Platform (CDP) x402 SDK to handle the payment flow. This library abstracts the complex blockchain interactions, allowing your Next.js application to focus on the verification logic rather than transaction management.

1
Install the x402 SDK

Open your terminal and navigate to your project root. Install the official x402 package using your preferred package manager. This package provides the core utilities for creating and validating x402-compliant endpoints.

Shell
Shell
npm install @coinbase/x402

If you are using TypeScript, you may also want to install the type definitions to ensure full IDE support for the SDK's API.

2
Configure environment variables

Create a .env.local file in your project root if it doesn't already exist. You need to store your Coinbase API credentials securely. Add the following variables, replacing the placeholders with your actual keys from the Coinbase Developer Portal:

Shell
Shell
COINBASE_API_KEY=your_api_key_here
COINBASE_API_SECRET=your_api_secret_here
COINBASE_NETWORK=base-sepolia # or mainnet for production

Never commit this file to version control. These keys are required for the middleware to authenticate payment requests on the blockchain.

3
Create the middleware handler

In your Next.js app directory, create a new file at src/lib/x402-middleware.ts. This file will export a function that wraps your API route logic. The middleware intercepts incoming requests, verifies the x402 payment signature, and only proceeds if the payment is valid.

TypeScript
TypeScript
import { x402Middleware } from '@coinbase/x402';

export const withX402 = (handler: any) => {
  return x402Middleware(handler, {
    network: process.env.COINBASE_NETWORK,
    apiKey: process.env.COINBASE_API_KEY,
    apiSecret: process.env.COINBASE_API_SECRET,
  });
};

This wrapper ensures that every protected endpoint checks for payment compliance before executing your KYC/AML verification logic.

4
Apply middleware to API routes

Finally, wrap your existing API route handlers with the withX402 function. For example, if you have a route at src/app/api/kyc/route.ts, import the middleware and apply it to your POST handler.

TypeScript
TypeScript
import { NextResponse } from 'next/server';
import { withX402 } from '@/lib/x402-middleware';

export const POST = withX402(async (request: Request) => {
  // Your KYC/AML verification logic goes here
  const data = await request.json();
  return NextResponse.json({ status: 'verified' });
});

Your endpoint is now protected. Any client attempting to call this API must include a valid x402 payment header, or the request will be rejected immediately.

With the middleware in place, your API is ready to accept USDC payments. The next step is to implement the actual KYC verification logic that will be triggered only after payment is confirmed.

Integrate KYC verification logic

Embedding KYC/AML checks into your x402 endpoint ensures that financial access is gated behind verified identity. Instead of treating compliance as an afterthought, you build the verification workflow directly into the request lifecycle. This approach aligns with the four pillars of KYC: Customer Acceptance Policy, Customer Identification Procedures (CIP), Transaction Monitoring, and Risk Management.

1
Define the CIP payload

Start by structuring the request to include Customer Identification Program data. The endpoint should accept standard identity fields such as full name, date of birth, and government-issued ID numbers. This data forms the basis of the initial identity check required by most regulatory frameworks.

2
Trigger the CDD check

Once the basic identity is captured, the endpoint must initiate Customer Due Diligence (CDD). This involves cross-referencing the provided information against internal risk databases and external watchlists. The verification logic should pause further processing until this risk assessment returns a clear status.

3
Enforce access control

Configure the x402 endpoint to deny access if the CDD check fails or returns a high-risk flag. Only when the identity is verified and the risk profile is acceptable should the endpoint proceed to process the transaction or grant API access. This ensures that only compliant users can interact with your financial services.

4
Log for ongoing monitoring

Finally, ensure that every verification attempt is logged. Ongoing monitoring is a critical part of the KYC process, allowing you to detect suspicious activity changes over time. These logs serve as your audit trail for regulatory reviews and help maintain the integrity of your compliance framework.

Structure payment schemes for access

x402 defines two distinct payment schemes for API access: exact and upto. Choosing the right one depends on whether your KYC/AML service requires strict, fixed-price verification or flexible, volume-based billing. The exact scheme locks the price per request, while upto allows the seller to adjust the price up to a pre-approved limit.

Choose exact for fixed-price verification

Use the exact scheme when your KYC checks have a predictable, flat cost per transaction. This is ideal for standard identity verification or document checks where the price per request never changes. The buyer’s wallet must have sufficient balance to cover the exact amount before the request is processed. This approach simplifies accounting for both you and your client, as there are no surprises in the final charge.

Use upto for dynamic or volume-based billing

The upto scheme is better suited for complex KYC workflows that involve multiple steps or variable costs. For example, a high-risk customer review might require additional manual checks, increasing the cost beyond the initial estimate. With upto, you set a maximum price limit during the initial request. The actual charge can be lower, but never higher than the limit. This flexibility protects buyers from unexpected overages while allowing you to bill accurately for the actual work performed.

Compare the schemes side-by-side

FeatureExact SchemeUpto Scheme
Price ControlFixed per requestUp to a set maximum
Best ForStandard, flat-rate checksComplex, variable-cost workflows
Buyer RiskLow (exact charge)Medium (up to limit)
Seller FlexibilityNoneHigh (can charge less)
FeatureExact SchemeUpto Scheme
Price ControlFixed per requestUp to a set maximum
Best ForStandard, flat-rate checksComplex, variable-cost workflows
Buyer RiskLow (exact charge)Medium (up to limit)
Seller FlexibilityNoneHigh (can charge less)

Test the endpoint flow

Before you push to production, you need to verify that the x402 payment loop actually triggers the verification you expect. A broken loop leaves users stuck between a payment screen and a pending KYC status. Use this sequence to validate the handshake between your API, the x402 payment layer, and your compliance provider.

1
Set up a sandbox environment

Use a dedicated test instance for your KYC provider and a sandbox mode for the x402 payment gateway. This prevents real funds from moving and keeps your compliance logs clean. Ensure your test users have distinct IDs so you can trace the flow from payment to verification without noise.

2
Simulate a successful payment

Send a test transaction to your x402 endpoint. Confirm that the payment status updates to paid and that the webhook fires correctly. Your system should immediately recognize the payment and queue the user for KYC checks. If the webhook fails, the user never gets verified, regardless of whether they paid.

3
Trigger the KYC verification

Once the payment is confirmed, initiate the KYC/AML check. Use a test identity that is known to pass verification (like a valid, unflagged ID). Verify that your API receives the positive result from the provider and updates the user’s status to verified. This confirms the happy path works end-to-end.

4
Test failure and rejection scenarios

A robust system must handle failure gracefully. Send a test identity that should be rejected (e.g., expired ID or high-risk profile). Ensure the system correctly flags the user as rejected or pending_review and does not grant access. Also, test a failed payment to ensure the user is not verified if the payment does not clear.

5
Verify compliance logging

Finally, check that all steps are logged for audit purposes. Regulatory bodies require proof that you performed due diligence. Ensure your logs capture the payment ID, the verification request timestamp, the provider’s response, and the final user status. This log is your proof of compliance if an audit occurs.

Common kyc/aml integration: what to check next

Developers building x402 endpoints for KYC/AML checks often hit the same technical and compliance walls. Below are the most frequent questions we see, focused on implementation rather than theory.

When integrating these checks into your x402 endpoint, remember that the data flow must mirror this sequence. You cannot skip verification for risk profiling, and you cannot replace ongoing monitoring with a one-time check. The endpoint should handle the state transitions between these steps, ensuring that each stage is completed before the next payment or transaction is authorized.