Express Integration

The @shade402/express package provides middleware and utilities for implementing X402 payment-protected endpoints in Express.js applications.

Installation

pnpm add @shade402/express @shade402/core

Basic Setup

Initialize Configuration

Initialize X402 with your payment configuration:

import { initX402 } from '@shade402/express';

initX402({
  paymentAddress: process.env.PAYMENT_WALLET_ADDRESS!,
  tokenMint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', // USDC
  network: 'solana-devnet',
  rpcUrl: process.env.SOLANA_RPC_URL,
  defaultAmount: '0.01',
  paymentTimeout: 300, // 5 minutes
  autoVerify: true,
});

Protect Routes

Use the paymentRequired middleware to protect routes:

Configuration Options

Global Configuration

Per-Route Configuration

You can override global configuration for specific routes:

Accessing Payment Information

Payment information is available on the request object after verification:

Error Handling

Add the error middleware at the end of your middleware stack:

The error middleware handles:

  • PaymentRequiredError: Returns 402 with payment request

  • PaymentExpiredError: Returns 410 Gone

  • InsufficientFundsError: Returns 402

  • PaymentVerificationError: Returns 403 Forbidden

  • TransactionBroadcastError: Returns 502 Bad Gateway

  • InvalidPaymentRequestError: Returns 400 Bad Request

Resource Encryption

Enable resource encryption for enhanced privacy:

With encryption enabled, the server will:

  • Include public key in 402 response headers

  • Automatically decrypt encrypted resource from client requests

  • Make decrypted resource available via req.decryptedResource

Multiple Payment Tiers

Implement different payment tiers:

Manual Payment Verification

For custom verification logic, disable automatic verification:

Building 402 Responses Manually

For custom payment flow control:

Complete Example

Best Practices

  1. Initialize X402 configuration once at application startup

  2. Store sensitive configuration in environment variables

  3. Use appropriate payment amounts for different tiers

  4. Set reasonable expiration times for payment requests

  5. Enable automatic verification in production

  6. Add error middleware after all routes

  7. Use TypeScript types for better type safety

  8. Monitor payment verification failures

  9. Consider rate limiting for payment-protected endpoints

  10. Log payment transactions for audit purposes

Next Steps

Last updated