npm package: @shade402/nextjs
Description: Next.js middleware and utilities for X402 payment protocol
Author: shade402
Latest version: 0.0.1

# @shade402/nextjs

Next.js middleware and utilities for implementing the X402 payment protocol in your Next.js applications.

## Overview

The Next.js package provides middleware and helper functions to easily add X402 payment requirements to your Next.js API routes. It handles payment verification, 402 response generation, and integrates seamlessly with Solana blockchain payments in Next.js App Router applications.

## Features

- Payment middleware for protecting Next.js API routes
- Automatic payment verification using Solana blockchain
- Flexible configuration with global or per-route options
- 402 response builder for creating proper payment requests
- Full TypeScript support with Next.js types
- App Router compatible
- Support for Next.js 13+ App Router

## Installation

```bash
npm install @shade402/nextjs
# or
pnpm add @shade402/nextjs
# or
yarn add @shade402/nextjs
```

## Dependencies

- `@shade402/core`: Core X402 protocol implementation
- `next`: Next.js framework (peer dependency)

## Peer Dependencies

- `next >= 13.0.0`: Next.js 13 or higher required

## Usage

### Basic Setup with Global Configuration

```typescript
// app/api/config/route.ts
import { initX402 } from '@shade402/nextjs';

// Initialize X402 with global configuration
initX402({
  paymentAddress: process.env.PAYMENT_WALLET_ADDRESS!,
  tokenMint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', // USDC
  network: 'solana-devnet',
  rpcUrl: process.env.SOLANA_RPC_URL,
  autoVerify: true
});
```

### Protecting API Routes

```typescript
// app/api/premium-content/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { withPayment } from '@shade402/nextjs';

export const GET = withPayment(
  {
    amount: '0.01',
    description: 'Access to premium content'
  },
  async (req: NextRequest, context) => {
    // This code only runs after payment is verified
    return NextResponse.json({
      content: 'Premium content here',
      paidBy: context.payment?.publicKey
    });
  }
);
```

### Per-Route Configuration

You can override global configuration for specific routes:

```typescript
// app/api/data/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { withPayment } from '@shade402/nextjs';

export const GET = withPayment(
  {
    amount: '0.005',
    paymentAddress: 'SpecificWalletAddress',
    tokenMint: 'So11111111111111111111111111111111111111112', // Native SOL
    network: 'solana-mainnet',
    description: 'API data access',
    expiresIn: 300, // 5 minutes
    autoVerify: true
  },
  async (req: NextRequest, context) => {
    return NextResponse.json({ data: 'Your data here' });
  }
);
```

### POST Route Example

```typescript
// app/api/submit/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { withPayment } from '@shade402/nextjs';

export const POST = withPayment(
  {
    amount: '0.01',
    description: 'Submission fee'
  },
  async (req: NextRequest, context) => {
    const body = await req.json();
    
    // Process submission
    return NextResponse.json({
      success: true,
      paymentId: context.payment?.paymentId
    });
  }
);
```

## API Reference

### initX402

Initialize global X402 configuration.

```typescript
function initX402(options: X402ConfigOptions): void
```

**Parameters:**
- `options.paymentAddress`: Wallet address to receive payments
- `options.tokenMint`: Token mint address (e.g., USDC)
- `options.network`: Network identifier (default: 'solana-devnet')
- `options.rpcUrl`: Optional Solana RPC URL
- `options.defaultAmount`: Default payment amount (default: '0.01')
- `options.paymentTimeout`: Payment timeout in seconds (default: 300)
- `options.autoVerify`: Automatically verify payments (default: true)

### withPayment

Higher-order function that wraps a Next.js API route handler with payment verification.

```typescript
function withPayment<T = any>(
  options: PaymentRequiredOptions,
  handler: X402Handler<T>
): (req: NextRequest) => Promise<NextResponse>
```

**Parameters:**
- `options`: Payment configuration options
  - `amount`: Required payment amount
  - `paymentAddress`: Optional payment address (uses global config if not provided)
  - `tokenMint`: Optional token mint (uses global config if not provided)
  - `network`: Optional network (uses global config if not provided)
  - `description`: Optional payment description
  - `expiresIn`: Optional expiration time in seconds
  - `autoVerify`: Optional auto-verify setting
- `handler`: Next.js API route handler function

**Handler Signature:**
```typescript
type X402Handler<T = any> = (
  req: NextRequest,
  context: X402HandlerContext
) => Promise<NextResponse<T>> | NextResponse<T>
```

**Context:**
- `context.payment`: Payment authorization object if payment was verified

### getConfig

Get current global configuration.

```typescript
function getConfig(): X402Config | null
```

### isInitialized

Check if X402 has been initialized.

```typescript
function isInitialized(): boolean
```

### build402Response

Build a 402 Payment Required response.

```typescript
function build402Response(options: Build402ResponseOptions): NextResponse
```

## Examples

### Multiple HTTP Methods

```typescript
// app/api/resource/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { withPayment } from '@shade402/nextjs';

const paymentOptions = {
  amount: '0.01',
  description: 'Resource access'
};

export const GET = withPayment(paymentOptions, async (req, context) => {
  return NextResponse.json({ data: 'Resource data' });
});

export const POST = withPayment(paymentOptions, async (req, context) => {
  const body = await req.json();
  return NextResponse.json({ success: true });
});
```

### Dynamic Payment Amounts

```typescript
// app/api/tiered/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { withPayment } from '@shade402/nextjs';

export const GET = withPayment(
  {
    amount: '0.01', // Base amount
    description: 'Tiered access'
  },
  async (req: NextRequest, context) => {
    const tier = req.nextUrl.searchParams.get('tier');
    const amount = tier === 'premium' ? '0.05' : '0.01';
    
    // Note: Amount is set in middleware, this is just for display
    return NextResponse.json({
      tier,
      amount,
      paymentId: context.payment?.paymentId
    });
  }
);
```

### Error Handling

```typescript
// app/api/error-handling/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { withPayment } from '@shade402/nextjs';

export const GET = withPayment(
  {
    amount: '0.01',
    description: 'Error handling example'
  },
  async (req: NextRequest, context) => {
    try {
      // Your logic here
      return NextResponse.json({ success: true });
    } catch (error) {
      return NextResponse.json(
        { error: 'Internal server error' },
        { status: 500 }
      );
    }
  }
);
```

### Accessing Payment Information

```typescript
// app/api/payment-info/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { withPayment } from '@shade402/nextjs';

export const GET = withPayment(
  {
    amount: '0.01',
    description: 'Payment information'
  },
  async (req: NextRequest, context) => {
    if (!context.payment) {
      return NextResponse.json(
        { error: 'No payment information' },
        { status: 500 }
      );
    }

    return NextResponse.json({
      paymentId: context.payment.paymentId,
      publicKey: context.payment.publicKey,
      transactionHash: context.payment.transactionHash,
      nonce: context.payment.nonce
    });
  }
);
```

## Configuration

### Environment Variables

Set these in your `.env.local` file:

```env
PAYMENT_WALLET_ADDRESS=YourSolanaWalletAddress
SOLANA_RPC_URL=https://api.devnet.solana.com
```

For production:

```env
PAYMENT_WALLET_ADDRESS=YourProductionWalletAddress
SOLANA_RPC_URL=https://your-mainnet-rpc-url.com
NETWORK=solana-mainnet
```

### Global Configuration

Initialize once in your application (e.g., in a config file or middleware):

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

initX402({
  paymentAddress: process.env.PAYMENT_WALLET_ADDRESS!,
  tokenMint: process.env.TOKEN_MINT || 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
  network: process.env.NETWORK || 'solana-devnet',
  rpcUrl: process.env.SOLANA_RPC_URL,
  defaultAmount: '0.01',
  paymentTimeout: 300,
  autoVerify: true
});
```

## TypeScript Support

The package is written in TypeScript and provides full type definitions:

```typescript
import type {
  X402ConfigOptions,
  PaymentRequiredOptions,
  X402Handler,
  X402HandlerContext,
  Build402ResponseOptions
} from '@shade402/nextjs';
```

## Next.js App Router Compatibility

This package is designed for Next.js 13+ App Router. For Pages Router support, use `@shade402/express` with a custom API server or Next.js API routes.

## Security Considerations

- Always use environment variables for sensitive configuration
- Enable auto-verification for production deployments
- Use HTTPS for all API routes
- Validate payment amounts before processing
- Never expose private keys in client-side code
- Use mainnet RPC endpoints for production
- Monitor payment transactions for suspicious activity

## Differences from Express Package

The Next.js package is similar to the Express package but adapted for Next.js App Router:

- Uses `withPayment` higher-order function instead of middleware
- Works with Next.js `NextRequest` and `NextResponse` types
- Handlers receive a context object instead of modifying request object
- No Express-specific error middleware (handle errors in your handlers)

## License

MIT