Overview
The Prism Express Middleware is a drop-in solution for protecting your Node.js API routes with blockchain-based micropayments using the x402 protocol.Zero Config
Type Safe
Flexible Pricing
What’s New in v1.1
Structured Error Handling
Structured Error Handling
PrismGatewayError- Preserves Gateway status codes and trace IDsPrismNetworkError- Network connectivity issues (503)PrismConfigError- SDK misconfiguration (500)PrismPaymentError- Invalid payment (402)PrismValidationError- Request validation (400)
- ✅ Type-safe error handling with
instanceofchecks - ✅ Gateway trace IDs for backend correlation
- ✅ Timestamps for log searching
- ✅ Original status codes preserved (not all converted to 500)
Gateway Trace IDs
Gateway Trace IDs
Payment Verification
Payment Verification
verifyPayment() endpoint integration:- Cryptographic signature verification via Gateway
- Payer address extracted and stored in
res.locals.payer - Proper error handling for verification failures
Improved Error Responses
Improved Error Responses
After: Detailed error with trace ID and timestamp
Installation
- npm
- yarn
- pnpm
@1stdigital Package:
prism-expressidentifyToken (PRISM_IDENTIFY_TOKEN env var) — formerly apiKey / PRISM_API_KEY. SDKs accept the legacy names as fallback during the migration window; new code should use the canonical names.Quick Start
Install Package
Import Middleware
Configure Middleware
Add Protected Route
Basic Usage
Configuration
Middleware Config
The first parameter toprismPaymentMiddleware is the global configuration:
https://prism-gw.fd.xyz.Route Configuration
The second parameter defines which routes require payment:0.001 (USDC) - String:
"$0.001" (explicit USD) - String: "0.001 USDC" (explicit token)
application/json - text/html -
image/png - video/mp4Route Patterns
Exact Match
- ✅
/api/weather - ❌
/api/weather/forecast - ❌
/api/weather-data
Wildcard Routes
- ✅
/api/premium/data - ✅
/api/premium/analytics - ✅
/api/premium/users/123 - ❌
/api/public/data
Multiple Routes
Route Priority
When multiple patterns match, most specific wins:/api/premium/gold → uses 0.05 price
Accessing Payment Info
Payment details are available in route handlers viares.locals.payment:
Payment Object Type
Error Handling
The SDK provides structured error handling with specific error classes, detailed error messages, and Gateway tracing information.Error Classes
All Prism errors extend the basePrismError class and include:
- Status code - HTTP status code to return
- Error code - Machine-readable error identifier
- Message - Human-readable error description
- Details - Additional context (varies by error type)
PrismGatewayError - Gateway returned an error
PrismGatewayError - Gateway returned an error
statusCode- Original HTTP status from Gateway (400, 401, 500, etc.)message- Error title from Gatewaydetails- Detailed error descriptiontraceId- Gateway trace ID for debuggingtimestamp- Error timestamp from Gateway
PrismNetworkError - Network/connectivity issues
PrismNetworkError - Network/connectivity issues
message- Network error descriptionoriginalError- Original axios/network error
PrismConfigError - Invalid configuration
PrismConfigError - Invalid configuration
message- Configuration error descriptiondetails- Configuration problem details
PrismPaymentError - Invalid payment
PrismPaymentError - Invalid payment
message- Payment validation errordetails- Why payment is invalid
PrismValidationError - Bad request data
PrismValidationError - Bad request data
message- Validation error messagefield- Field that failed validationdetails- Validation error details
Error Response Format
All error responses follow a consistent structure:Advanced Error Handling
1. Monitoring & Alerting with Trace IDs
2. Retry Logic with Exponential Backoff
3. User-Friendly Error Messages
4. Error Metrics & Analytics
Debugging with Trace IDs
When reporting issues to Prism support, always include the trace ID from error responses:Advanced Usage
Environment-Based Configuration
Accessing Payment Details
After successful payment verification, payment details are available inres.locals:
Rate Limiting with Payments
Combine with rate limiting for hybrid monetization:TypeScript Support
Full Type Definitions
Express Types Extension
Add types tores.locals:
Testing
Unit Tests
Integration Tests with Sandbox
Performance Optimization
Caching Payment Requirements
Connection Pooling
Migration Guide
From v0.x to v1.x
Update Package
Update Import
Update Configuration
Troubleshooting
402 responses not working
402 responses not working
- Verify middleware is registered before route handlers
- Check route paths match exactly (case-sensitive)
- Ensure
identifyTokenis valid - Check Gateway connectivity (
curl https://prism-gw.fd.xyz/health)
Gateway timeout errors
Gateway timeout errors
503 Service Unavailable or PrismNetworkErrorSolutions:- Check network connectivity to Gateway
- Verify no firewall blocking outbound HTTPS to
prism-gw.fd.xyz - Check Gateway status page
- Implement retry logic (see Error Handling section)
Invalid Project Identify Token errors
Invalid Project Identify Token errors
401 Unauthorized or PrismGatewayError with status 401Solutions:- Verify Project Identify Token in Client Portal
- Check environment variable:
echo $PRISM_IDENTIFY_TOKEN - Ensure key hasn’t been revoked
- Use correct environment (sandbox vs production)
Gateway 500 errors with trace ID
Gateway 500 errors with trace ID
PrismGatewayError with status 500 and trace IDSolutions:- This is a Gateway backend issue - not your code
- Extract and log the
traceIdfrom error - Report to Prism support with trace ID
TypeScript compilation errors
TypeScript compilation errors
- Install type definitions:
npm install -D @types/express - Update
tsconfig.json:"moduleResolution": "node" - Ensure TypeScript version >= 4.5
API Reference
prismPaymentMiddleware(config, routes)
Creates Express middleware for x402 payment protection.
Parameters:
config(PrismMiddlewareConfig) - Global configurationroutes(Record<string, RoutePaymentConfig>) - Route payment settings
Error Classes
PrismError (Base Class)
Base error class for all Prism SDK errors.
Properties:
message(string) - Error messagecode(string) - Error code (e.g., ‘GATEWAY_ERROR’, ‘NETWORK_ERROR’)statusCode(number) - HTTP status codedetails(any) - Additional error context
toJSON()- Convert error to JSON representation
PrismGatewayError extends PrismError
Gateway returned an error response (4xx or 5xx).
Additional Properties:
traceId(string | undefined) - Gateway trace ID for debuggingtimestamp(string | undefined) - ISO 8601 timestamp from Gateway
PrismNetworkError extends PrismError
Network connectivity issues (timeout, DNS error, connection refused).
Additional Properties:
originalError(any) - Original network error from axios
PrismConfigError extends PrismError
SDK misconfiguration (invalid Project Identify Token format, bad URL, etc.).
Status Code: Always 500
Example:
PrismPaymentError extends PrismError
Invalid payment payload or authorization.
Status Code: Always 402
Example:
PrismValidationError extends PrismError
Request validation failed.
Additional Properties:
field(string | undefined) - Field that failed validation