x402-next
package.
Installation
First, install the required package:Basic Setup
Create amiddleware.ts
file in your project root (or src/
directory if using that structure):
Configuration Parameters
Contract Configuration
contractAddress
: The address of the Meridian deployed X402 contractnetwork
: The blockchain network (e.g., “base”, “ethereum”, “polygon”)
Route Protection
The second parameter defines which routes should be protected and their pricing:Facilitator Configuration
The third parameter configures the facilitator service:Route Matching
Configure which routes the middleware should protect using theconfig
export:
Advanced Configuration
Multiple Networks
You can configure different networks for different routes:Dynamic Pricing
For dynamic pricing based on user or content, you can use functions:Meridian Auth Headers
Implement Meridian authentication logic:Error Handling
The middleware automatically handles common error scenarios:- Insufficient funds: Shows payment UI
- Network errors: Displays appropriate error messages
- Invalid configuration: Logs errors and falls back gracefully
Testing
To test your middleware integration:- Start your development server:
npm run dev
- Navigate to a protected route (e.g.,
/protected/test
) - The middleware should intercept the request and show the payment UI
- Complete a test payment to verify the flow
Production Considerations
- Ensure all environment variables are properly set
- Use HTTPS in production
- Monitor facilitator service health
- Implement proper error logging
- Consider rate limiting for payment endpoints
Troubleshooting
Common Issues
Middleware not running:- Check that
middleware.ts
is in the correct location - Verify the
matcher
configuration includes your routes
- Verify environment variables are set correctly
- Check facilitator service connectivity
- Ensure contract address is valid
- Verify API keys are correct
- Check facilitator service authentication requirements