Security
Always Validate Requests
Always Validate Requests
This is the most critical security practice. Before processing any request to a protected endpoint, you must validate the incoming request to ensure the user is an authorized subscriber with sufficient credits.
Secure Your API Keys
Secure Your API Keys
Never hardcode API keys or other secrets in your source code. Use environment variables to manage your credentials securely.
Implement Rate Limiting
Implement Rate Limiting
Protect your agent from denial-of-service (DoS) attacks and abuse by implementing rate limiting. This ensures fair usage and maintains service availability.
Fail Closed
Fail Closed
In case of an unexpected error during the validation process, your application should “fail closed”—meaning it should deny access by default rather than granting it.
Performance
Cache Agent and Plan Data
Cache Agent and Plan Data
Your agent’s metadata and its payment plans don’t change frequently. Cache this data in your application to reduce latency and minimize API calls to Nevermined.
Batch Operations When Possible
Batch Operations When Possible
When you need to perform the same operation multiple times (e.g., fetching details for several agents), use
Promise.all to run them in parallel instead of sequentially.User Experience
Provide Clear Payment-Required Messages
Provide Clear Payment-Required Messages
When a user without access tries to use your service, provide a clear error message along with the
paymentCard so they know exactly how to gain access.Inform Users About Their Usage
Inform Users About Their Usage
Use response headers to provide subscribers with real-time information about their credit balance. This transparency helps build trust and improves the user experience.
Implementation Patterns
Middleware Pattern
Create reusable middleware for authentication:Error Handling Pattern
Implement comprehensive error handling:Monitoring and Analytics
Track Revenue
Monitor your agent’s revenue generation:Monitor Agent Health
Implement health checks and monitoring:Testing Recommendations
Use Testing Environment
Always use the testing environment during development:Mock for Unit Tests
Mock the Payments SDK for unit testing:Integration Testing
Test the full flow in a test environment:Summary
Following these best practices will help you build secure, performant, and user-friendly AI agents with Nevermined Payments. Remember to:- Always validate requests before processing
- Secure your API keys and sensitive data
- Implement proper error handling
- Cache data for better performance
- Provide clear feedback to users
- Monitor your agents’ health and usage
- Test thoroughly in development environments