Next.js Integration

The @shade402/nextjs package provides middleware and utilities for implementing X402 payment-protected routes in Next.js applications.

Installation

pnpm add @shade402/nextjs @shade402/core

Setup

Initialize Configuration

Initialize X402 in your Next.js application. Create a configuration file:

// lib/x402-config.ts
import { initX402 } from '@shade402/nextjs';

export function configureX402() {
  if (typeof window === 'undefined') {
    // Server-side only
    initX402({
      paymentAddress: process.env.PAYMENT_WALLET_ADDRESS!,
      tokenMint: process.env.TOKEN_MINT!,
      network: process.env.SOLANA_NETWORK || 'solana-devnet',
      rpcUrl: process.env.SOLANA_RPC_URL,
      autoVerify: true,
      defaultAmount: '0.01',
      paymentTimeout: 300,
    });
  }
}

Call this in your API routes or middleware:

API Routes

Protect API routes using the withPayment wrapper:

Pages Router

For Pages Router (app/pages directory):

Configuration Options

Accessing Payment Information

Payment information is available in the handler context:

Error Handling

The withPayment wrapper automatically handles errors and returns appropriate HTTP status codes:

  • 402: Payment required

  • 403: Payment verification failed

  • 410: Payment expired

  • 500: Internal server error

For custom error handling, you can catch errors in your handler:

Multiple Payment Tiers

Implement different payment tiers:

Environment Variables

Set up environment variables in .env.local:

Complete Example

Client-side Integration

For client-side requests, use the @shade402/client package:

Best Practices

  1. Initialize X402 configuration in a shared utility file

  2. Store sensitive configuration in environment variables

  3. Use appropriate payment amounts for different routes

  4. Enable automatic verification in production

  5. Use TypeScript types for better type safety

  6. Handle errors gracefully in your handlers

  7. Consider rate limiting for payment-protected routes

  8. Log payment transactions for audit purposes

Next Steps

Last updated