Skip to main content

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

Works out of the box with Express.js

Type Safe

Full TypeScript support with IntelliSense

Flexible Pricing

Per-route pricing with wildcards

What’s New in v1.1

Latest Version: 1.1.0 - Enhanced error handling and Gateway integration
New error classes for better debugging and monitoring:
  • PrismGatewayError - Preserves Gateway status codes and trace IDs
  • PrismNetworkError - Network connectivity issues (503)
  • PrismConfigError - SDK misconfiguration (500)
  • PrismPaymentError - Invalid payment (402)
  • PrismValidationError - Request validation (400)
Benefits:
  • ✅ Type-safe error handling with instanceof checks
  • ✅ Gateway trace IDs for backend correlation
  • ✅ Timestamps for log searching
  • ✅ Original status codes preserved (not all converted to 500)
Debug production issues faster with Gateway trace IDs:
Include trace IDs in support tickets for faster resolution.
Implemented verifyPayment() endpoint integration:
  • Cryptographic signature verification via Gateway
  • Payer address extracted and stored in res.locals.payer
  • Proper error handling for verification failures
Better error messages for end-users:
Before: Generic “Failed to generate payment requirements”
After: Detailed error with trace ID and timestamp

Installation

Package Registry: GitHub Packages Scope: @1stdigital Package: prism-express
The canonical SDK config is identifyToken (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

1

Install Package

2

Import Middleware

3

Configure Middleware

4

Add Protected Route

Basic Usage

Configuration

Middleware Config

The first parameter to prismPaymentMiddleware is the global configuration:
string
required
Your Prism Project Identify Token from Client Portal
Store in environment variable: process.env.PRISM_IDENTIFY_TOKEN
string
Prism Gateway URL. Defaults to https://prism-gw.fd.xyz.
number
default:"10000"
Request timeout in milliseconds
Gateway calls that exceed timeout will fail gracefully
number
default:"3"
Number of retry attempts for failed Gateway requests

Route Configuration

The second parameter defines which routes require payment:
number | string
required
Price to charge per request Formats: - Number: 0.001 (USDC) - String: "$0.001" (explicit USD) - String: "0.001 USDC" (explicit token)
Use small decimals for micropayments: 0.001 = $0.001 = 0.1¢
string
Human-readable description shown to users
Use ASCII characters (U+0000–U+007F) in description for best HTTP header compatibility. This value is transmitted in payment-related HTTP headers, where non-ASCII characters (e.g., em dashes, curly quotes, accented letters) may cause encoding issues across SDKs. If you need to display a Unicode description to end users, keep a separate display string in your application code.
string
default:"application/json"
Response content type Common values: - application/json - text/html - image/png - video/mp4
number
default:"300"
Maximum time (seconds) to wait for payment
After timeout, payment authorization expires
string
Custom resource URL (overrides request path)

Route Patterns

Exact Match

Matches:
  • /api/weather
  • /api/weather/forecast
  • /api/weather-data

Wildcard Routes

Matches:
  • /api/premium/data
  • /api/premium/analytics
  • /api/premium/users/123
  • /api/public/data

Multiple Routes

Route Priority

When multiple patterns match, most specific wins:
Request to /api/premium/gold → uses 0.05 price

Accessing Payment Info

Payment details are available in route handlers via res.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 base PrismError 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)
When: Prism Gateway API returns 4xx or 5xx responseProperties:
  • statusCode - Original HTTP status from Gateway (400, 401, 500, etc.)
  • message - Error title from Gateway
  • details - Detailed error description
  • traceId - Gateway trace ID for debugging
  • timestamp - Error timestamp from Gateway
Example Response:
Usage:
When: Cannot reach Prism Gateway (timeout, DNS error, connection refused)Status Code: 503 Service UnavailableProperties:
  • message - Network error description
  • originalError - Original axios/network error
Example Response:
Usage (Retry Logic):
When: SDK is misconfigured (invalid Project Identify Token format, bad URL, etc.)Status Code: 500 Internal Server ErrorProperties:
  • message - Configuration error description
  • details - Configuration problem details
Example Response:
Usage:
When: Payment payload is malformed or invalidStatus Code: 402 Payment RequiredProperties:
  • message - Payment validation error
  • details - Why payment is invalid
Example Response:
When: Request data fails validation (negative price, missing fields, etc.)Status Code: 400 Bad RequestProperties:
  • message - Validation error message
  • field - Field that failed validation
  • details - Validation error details
Example Response:

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:
Example support ticket:

Advanced Usage

Environment-Based Configuration

.env.development:
.env.production:

Accessing Payment Details

After successful payment verification, payment details are available in res.locals:

Rate Limiting with Payments

Combine with rate limiting for hybrid monetization:

TypeScript Support

Full Type Definitions

Express Types Extension

Add types to res.locals:

Testing

Unit Tests

Integration Tests with Sandbox

Performance Optimization

Caching Payment Requirements

Connection Pooling

Migration Guide

From v0.x to v1.x

1

Update Package

2

Update Import

3

Update Configuration

Troubleshooting

Symptoms: Routes always return 200, no payment requiredSolutions:
  • Verify middleware is registered before route handlers
  • Check route paths match exactly (case-sensitive)
  • Ensure identifyToken is valid
  • Check Gateway connectivity (curl https://prism-gw.fd.xyz/health)
Symptoms: 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)
Example:
Symptoms: 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)
Check error details:
Symptoms: PrismGatewayError with status 500 and trace IDSolutions:
  • This is a Gateway backend issue - not your code
  • Extract and log the traceId from error
  • Report to Prism support with trace ID
Example:
Symptoms: Type errors during buildSolutions:
  • 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 configuration
  • routes (Record<string, RoutePaymentConfig>) - Route payment settings
Returns: Express middleware function Example:

Error Classes

PrismError (Base Class)

Base error class for all Prism SDK errors. Properties:
  • message (string) - Error message
  • code (string) - Error code (e.g., ‘GATEWAY_ERROR’, ‘NETWORK_ERROR’)
  • statusCode (number) - HTTP status code
  • details (any) - Additional error context
Methods:
  • toJSON() - Convert error to JSON representation
Example:

PrismGatewayError extends PrismError

Gateway returned an error response (4xx or 5xx). Additional Properties:
  • traceId (string | undefined) - Gateway trace ID for debugging
  • timestamp (string | undefined) - ISO 8601 timestamp from Gateway
Example:

PrismNetworkError extends PrismError

Network connectivity issues (timeout, DNS error, connection refused). Additional Properties:
  • originalError (any) - Original network error from axios
Status Code: Always 503 Example:

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
Status Code: Always 400 Example:

Error Codes

Resources

GitHub Repository

View source code and examples

npm Package

Package on GitHub Packages

API Reference

Prism Gateway REST API docs

Examples

Complete code examples
Last modified on May 21, 2026