Astro App Example with X402 Payment Support¶
This example demonstrates how to create an Astro application with X402 payment requirements for API endpoints, featuring server-side rendering, React component integration, and real Solana wallet payments.
Features¶
- Astro SSR - Server-side rendering with
@astrojs/nodeadapter - React Integration - Interactive payment UI with React components
- Server-side API Routes - Protected endpoints with payment requirements
- Phantom Wallet Support - Real blockchain transactions on Solana devnet
- Payment Simulation - Demo mode for testing without wallet/funds
- TypeScript - Full type safety across client and server
- Tailwind CSS - Modern, responsive styling
- X402 Protocol - HTTP 402 Payment Required standard
Setup¶
1. Install Dependencies¶
From the monorepo root:
Or from the examples/typescript/astro-app directory:
2. Configure Environment¶
Create a .env file based on .env.example:
Edit .env with your Solana wallet details:
3. Build and Run¶
The app will start on http://localhost:4321.
API Endpoints¶
Free Endpoints¶
- GET /api/free-data - Public data access (no payment required)
Paid Endpoints¶
- GET /api/premium-data - Premium data (0.10 USDC)
- GET /api/expensive-data - AI inference (1.00 USDC)
- GET /api/tiered-data/[tier] - Tiered content (0.05 USDC for premium)
- POST /api/process-data - Data processing (0.25 USDC)
How It Works¶
Server-Side (API Routes)¶
Astro API routes are located in src/pages/api/ and export request handlers:
- Initialize X402 Configuration (
src/utils/x402-config.ts):
- Protect API Routes with
withPaymenthelper:
Client-Side (React Components)¶
- Wallet Connection (
src/components/WalletButton.tsx):
- Payment Endpoint Card (
src/components/X402EndpointCard.tsx):
Payment Flow¶
Demo Mode (Simulated)¶
- User clicks "Try Endpoint" button
- Server responds with 402 Payment Required
- User clicks "Simulate Payment & Retry"
- Client generates mock authorization header
- Client retries request with authorization
- Server validates and returns content
Real Mode (Blockchain)¶
- User clicks "Connect Wallet" and approves Phantom connection
- User clicks "Try Endpoint" button
- Server responds with 402 Payment Required
- User clicks "💰 Pay with Phantom Wallet"
- Client creates Solana transaction and requests signature
- User approves transaction in Phantom wallet
- Transaction broadcasts to Solana devnet
- Client retries request with transaction details
- Server validates payment and returns content
- Transaction visible on Solscan
Real Wallet Integration¶
Setup Phantom Wallet for Testing¶
- Install Phantom: Download from phantom.app
- Switch to Devnet: Settings → Developer Settings → Testnet Mode → Solana Devnet
- Get SOL: Visit solfaucet.com and request free devnet SOL
- Connect: Click "Connect Wallet" button in the app
Real Payment Implementation¶
The src/utils/real-payment.ts utility handles actual blockchain transactions:
Verifying Transactions on Solscan¶
After a successful real payment:
- Copy the transaction signature from the UI response
- Visit:
https://solscan.io/tx/[SIGNATURE]?cluster=devnet - View transaction details including:
- Transaction status (Success/Failed)
- Signer (your wallet address)
- Recipient (payment wallet address)
- Amount and fees
- Block and timestamp
Project Structure¶
Configuration¶
Astro Config (astro.config.mjs)¶
Key configuration points:
@astrojs/node: Server-side rendering adapter (required for API routes)@astrojs/react: Enables React components with client-side interactivityoutput: 'server': Full SSR mode (not static or hybrid)- Vite SSR externals: Prevents bundling Solana packages server-side
Development Tips¶
Testing Workflow¶
- Start with Demo Mode: Use "Simulate Payment & Retry" to test the flow without wallet setup
- Test Free Endpoint: Verify basic API routing works correctly
- Set up Phantom: Only needed when testing real blockchain payments
- Check Browser Console: Detailed error messages appear in developer tools
Common Issues¶
"Phantom wallet not connected" - Solution: Click "Connect Wallet" button first - Verify Phantom extension is installed and enabled
"Insufficient SOL balance" - Solution: Visit solfaucet.com for free devnet SOL - Need at least 0.000005 SOL for transaction fees
"Payment address mismatch"
- Solution: Ensure .env file has correct PAYMENT_WALLET_ADDRESS
- Check address matches between client and server
"Transaction doesn't appear on Solscan"
- Verify you used "Pay with Phantom Wallet" (not simulate)
- Check correct cluster: ?cluster=devnet in URL
- Wait 30 seconds for confirmation
Hot Reload¶
Astro supports hot module replacement:
- Changes to .astro files reload automatically
- React component changes (.tsx) hot-reload
- API route changes require manual refresh
- .env changes require server restart
Production Considerations¶
Mainnet Deployment¶
For production on Solana mainnet:
- Update RPC URL: Use mainnet endpoint or dedicated provider
- Use Real USDC: Update
USDC_MINT_ADDRESSto mainnet USDC mint - Implement SPL Token Transfers: Replace SOL transfers with proper USDC token transfers
- On-chain Verification: Enable
autoVerifyin X402 config - Rate Limiting: Add rate limiting middleware
- Database Storage: Store payment receipts and transaction history
- Error Handling: Implement retry logic and user notifications
Security Best Practices¶
- Never expose private keys in client-side code
- Validate all inputs on server-side
- Use HTTPS for production deployments
- Implement CORS policies appropriately
- Monitor transactions for suspicious activity
- Test thoroughly on devnet before mainnet
Comparison with Other Frameworks¶
Astro vs Next.js¶
Astro Advantages: - Lighter JavaScript bundle (less client-side JS by default) - Flexible component framework (React, Vue, Svelte in one project) - Better static site performance
Next.js Advantages: - More mature ecosystem - Built-in API routes with middleware - Better TypeScript integration
Astro vs Nuxt¶
Astro Advantages: - Framework-agnostic (not tied to Vue) - Better performance for content-heavy sites - Simpler mental model
Nuxt Advantages: - Better for full Vue.js applications - More integrated dev experience with Vue ecosystem - Auto-imports and conventions
All three frameworks (Astro, Next.js, Nuxt) support X402 with similar implementation patterns.
Learn More¶
- OpenLibx402 Documentation
- X402 Protocol Specification
- Astro Documentation
- Phantom Wallet Docs
- Solana Web3.js
- Solscan Explorer
Additional Resources¶
For detailed setup instructions on real wallet payments, see REAL_PAYMENTS.md in the example directory.