Server Path
Lesson 2 of 8
15 min

Protecting Your First Endpoint

Learning Objectives

  • Install and configure x402-next
  • Protect an API route with withX402()
  • Test the protected endpoint
  • Understand what happens behind the scenes

The Easy Way

The withX402() middleware handles everything for you. Just wrap your API handler and it will:

Intercept incoming requests
Check for payment headers
Return 402 if no payment
Verify payment if provided
Call your handler only after successful payment
typescript
import { paymentMiddleware } from '@x402/express';
import { x402ResourceServer, HTTPFacilitatorClient } from '@x402/core/server';
import { registerExactEvmScheme } from '@x402/evm/exact/server';
import express from 'express';

// Setup facilitator client and server
const facilitatorClient = new HTTPFacilitatorClient({
  url: 'https://api.cdp.coinbase.com/platform/v2/x402'
});

const server = new x402ResourceServer(facilitatorClient);
registerExactEvmScheme(server);

// Create Express app
const app = express();

// Configure protected routes
app.use(
  paymentMiddleware(
    {
      'GET /api/data': {
        accepts: [{
          scheme: 'exact',
          price: '$0.001',
          network: 'eip155:8453', // Base
          payTo: process.env.RECEIVING_WALLET_ADDRESS!,
        }],
        description: 'Paid data endpoint',
        mimeType: 'application/json',
      },
    },
    server
  )
);

// Your handler - only runs after successful payment
app.get('/api/data', (req, res) => {
  res.json({ message: 'You paid for this data!' });
});

Testing Your Endpoint

You can test the endpoint with cURL or the x402 CLI:

bash
# This will return 402
curl https://localhost:3000/api/data

# This will work (using x402 client)
npx @x402/cli call https://localhost:3000/api/data

Interactive Playground

typescript
Output

Click "Run Code" to see the output