Skip to content

An Express.js starter template for building payment-gated HTTP APIs using the x402 protocol, powered by Oura402.

License

Notifications You must be signed in to change notification settings

Oura402/javascript-starter-project

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

10 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

x402 Express Starter

An Express.js starter template for building payment-gated HTTP APIs using the x402 protocol, powered by Oura402. Deploy production-ready cryptocurrency payment infrastructure in minutes.

Overview

x402 is an open payment protocol that leverages the HTTP 402 Payment Required status code to enable cryptocurrency payments through standard HTTP requests. This starter provides a battle-tested foundation for building payment-gated applications with minimal configuration.

Oura402 serves as the payment verification layer, abstracting blockchain complexity while maintaining protocol compliance. The result: production-grade payment infrastructure without specialized cryptographic knowledge.

Key Features

This starter template is optimized for rapid deployment and developer experience:

  • Rapid Deployment - Production-ready server in under 5 minutes with minimal configuration
  • Type-Safe Development - Full TypeScript support with comprehensive type definitions
  • Payment Middleware - Drop-in Express.js middleware for route-level payment gating
  • Multi-Chain Support - Native support for Base, Solana, and Ethereum networks
  • Flexible Pricing Models - Dollar-denominated pricing or custom token configurations
  • Managed Verification - Oura402 facilitator handles payment validation automatically
  • Comprehensive Testing - Complete test suite with unit and integration coverage
  • Production Ready - Environment configuration, error handling, and monitoring included

Quick Start

Prerequisites

  • Node.js 18+ (install via nvm recommended)
  • Wallet address for receiving payments (Ethereum/Base or Solana compatible)
  • Optional: Coinbase Developer Platform credentials for Base mainnet (obtain here)

Installation

Bootstrap a new project using npx:

# npm
npx @oura402/x402-sdk create my-payment-api

# pnpm
pnpm dlx @oura402/x402-sdk create my-payment-api

# bun
bunx @oura402/x402-sdk create my-payment-api

Configuration

Create your environment configuration:

cp .env-local .env

Update .env with your wallet address:

# Oura402 payment verification endpoint
FACILITATOR_URL=https://facilitator.oura402.dev

# Target blockchain network
NETWORK=base-sepolia  # Options: base-sepolia, base, solana-devnet, solana

# Payment recipient address
ADDRESS=0xYourWalletAddressHere

# Base mainnet only (optional for testnets)
CDP_API_KEY_ID=your_coinbase_platform_key_id
CDP_API_KEY_SECRET=your_coinbase_platform_secret

Development Server

# Install dependencies
npm install

# Start development server (http://localhost:4021)
npm run dev

# Run test suite
npm test

# Build for production
npm run build

Architecture

Technology Stack

Component Technology Purpose
Runtime Node.js 18+ JavaScript execution environment
Framework Express.js HTTP server and routing
Language TypeScript 5.7+ Type safety and developer experience
Payment Protocol x402 HTTP-native cryptocurrency payments
Verification Layer Oura402 Facilitator Blockchain payment validation
Testing Vitest + Supertest Unit and integration testing

Project Structure

x402-express-starter/
├── template/                    # Application template
│   ├── app.ts                  # Express application factory
│   ├── index.ts                # Server entry point
│   ├── .env-local              # Environment template
│   └── __tests__/              # Test suites
│       ├── app.test.ts         # Unit tests
│       ├── payment-flow.test.ts # Integration tests
│       └── README.md           # Testing documentation
├── bin/
│   └── create.js               # Project scaffolding CLI
├── scripts/
│   └── sanitize.sh             # Build tooling
├── TESTING.md                  # Comprehensive testing guide
├── package.json                # Package configuration
└── README.md                   # This file

Payment Flow Architecture

The x402 protocol implements a three-phase payment flow:

  1. Initial Request - Client requests protected resource without payment
  2. Payment Requirement - Server responds with 402 Payment Required and payment parameters
  3. Payment Submission - Client executes blockchain transaction
  4. Verification - Oura402 facilitator validates payment proof
  5. Content Delivery - Server grants access to protected resource
// Example: Payment-gated endpoint
app.get("/api/data", (req, res) => {
  // Middleware handles payment verification automatically
  // This code only executes after successful payment
  res.json({ data: "Premium content" });
});

Implementation Guide

Server Configuration

The starter includes a pre-configured Express application with payment middleware:

import express from "express";
import { paymentMiddleware } from "x402-express";

const app = express();

// Configure route-level payment requirements
app.use(
  paymentMiddleware(
    process.env.ADDRESS, // Payment recipient
    {
      "GET /weather": {
        price: "$0.001",              // Dollar-denominated pricing
        network: "base-sepolia",      // Target network
      },
      "POST /api/generate": {
        price: {
          amount: "1000000",          // Atomic units
          asset: {
            address: "0x...",         // Token contract
            decimals: 6,
            eip712: {
              name: "USDC",
              version: "1"
            },
          },
        },
        network: "base",
      },
    },
    {
      url: process.env.FACILITATOR_URL, // Oura402 verification
    }
  )
);

Network Configuration

Network Identifier Type Use Case
Base Sepolia base-sepolia Testnet Development and testing
Base Mainnet base Mainnet Production (requires CDP credentials)
Solana Devnet solana-devnet Testnet Solana development
Solana Mainnet solana Mainnet Solana production

Payment Requirements Format

Payment requirements follow the x402 specification:

interface PaymentRequirements {
  scheme: string;              // Payment scheme identifier
  network: string;             // Blockchain network
  payTo: string;              // Recipient address
  maxAmountRequired: string;  // Payment amount (atomic units)
  resource: string;           // Protected resource URL
  maxTimeoutSeconds: number;  // Payment timeout window
  asset: string;              // Token contract address
}

Testing

Running Tests

# Execute full test suite
npm test

# Watch mode for development
npm run test:watch

# Generate coverage report
npm run test:coverage

Test Coverage

The starter includes comprehensive test coverage:

  • Unit Tests - Express application configuration, middleware integration, route handling
  • Integration Tests - Complete payment flows, multi-endpoint scenarios, error conditions
  • Edge Cases - Concurrent requests, malformed payments, network timeouts

See TESTING.md for detailed testing documentation.

Deployment

Vercel (Recommended)

Optimized for Vercel serverless deployment:

# Install Vercel CLI
npm i -g vercel

# Deploy to preview
vercel

# Deploy to production
vercel --prod

Docker

FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --production
COPY . .
RUN npm run build
EXPOSE 4021
CMD ["npm", "start"]

Environment Variables

Configure the following in your deployment platform:

FACILITATOR_URL=https://facilitator.oura402.dev
NETWORK=base
ADDRESS=0xYourProductionWalletAddress
CDP_API_KEY_ID=your_key_id
CDP_API_KEY_SECRET=your_key_secret
PORT=4021  # Optional, defaults to 4021

Use Cases

This starter is production-ready for:

  • API Monetization - Usage-based billing for REST APIs
  • Premium Content Delivery - Paywalled data, media, or reports
  • AI/ML Inference Services - Per-request pricing for model inference
  • Data Access - Monetized datasets and analytics endpoints
  • Micropayment Workflows - High-volume, low-value transactions
  • SaaS Metering - Consumption-based pricing models
  • IoT Payment Networks - Machine-to-machine micropayments

Oura402 Integration

Verification Service

Oura402's facilitator service provides:

  • Instant Verification - Sub-second payment validation without RPC polling
  • Multi-Chain Support - Unified API across Base, Solana, and Ethereum
  • 99.9% Uptime SLA - Geographic redundancy and automatic failover
  • Real-time Settlement - WebSocket notifications for payment events
  • Zero Infrastructure - No blockchain nodes or key management required

API Endpoints

The facilitator exposes a REST API for payment verification:

POST https://facilitator.oura402.dev/verify
Content-Type: application/json

{
  "payment_proof": "0x...",
  "network": "base",
  "amount": "1000000",
  "recipient": "0x..."
}

See Oura402 API Documentation for complete specifications.

Development

Building from Source

# Clone repository
git clone https://github.com/Oura402/x402-express-starter.git
cd x402-express-starter

# Install dependencies
npm install

# Run in development mode
npm run dev

Local Package Linking

# In this repository
npm link

# In your application
npm link @oura402/x402-sdk

Contributing

We welcome contributions to improve the x402 Express Starter:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/enhancement)
  3. Commit changes with descriptive messages
  4. Ensure all tests pass (npm test)
  5. Submit a pull request

Review our contribution guidelines for code standards and review process.

Resources

Support

License

Apache-2.0. Portions derived from coinbase/x402. See LICENSE for details.


Built with x402 protocol | Secure, fast, HTTP-native cryptocurrency payments

About

An Express.js starter template for building payment-gated HTTP APIs using the x402 protocol, powered by Oura402.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published