Charge for HTTP requests with @bsv/402-pay
Use @bsv/402-pay to charge for HTTP routes with BitcoinSV (BSV) micropayments. A server answers a priced route with the status 402 Payment Required and the price. A client pays from a BRC-100BSV Request for Comments 100, the standard wallet interface for applications wallet and repeats the request. The package follows BRC-121The BSV blockchain standard for HTTP 402 micropayments and has a server side and a client side. For the full walkthrough, follow Gate an API behind payments.
Install
The latest version on npm is 0.3.5, with the status Beta, so its API can still change. It needs Node.js 22 or newer and @bsv/sdk. This page was written against @bsv/402-pay 0.3.5, @bsv/sdk 4.0.1 and @bsv/wallet-toolbox 2.15.1. The examples use top-level await, so use an ES module project (npm pkg set type=module). The server also needs Express and a wallet that receives the payments, here from @bsv/wallet-toolbox. In your project folder, run:
npm install express @bsv/402-pay@0.3.5 @bsv/sdk@4.0.1 @bsv/wallet-toolbox@2.15.1
npm install -D tsx @types/express @types/nodeWhat the package includes
The package has two entry points, one for the server and one for the client:
| Entry point | Export | What it does |
|---|---|---|
@bsv/402-pay/server | createPaymentMiddleware | Express middleware that prices a route and checks the payment |
@bsv/402-pay/server | validatePayment, send402 | The same two steps by hand, for a framework other than Express |
@bsv/402-pay/server | InMemoryPaymentReplayStore | Remembers the payments already used, so one payment unlocks one request |
@bsv/402-pay/client | create402Fetch | A fetch that pays from the wallet and repeats the request |
@bsv/402-pay/client | constructPaymentHeaders | Builds the payment headers without the fetch wrapper |
Example on testnet
The example runs on testnet. A server charges 1,000 satoshis for /premium and nothing for /free, and a client pays from BSV Desktop.
BSV Desktop must be on testnet with some testnet coins. A new BSV Desktop wallet opens on Mainnet, where coins have real value, so switch it to testnet and fund it from a faucet first, as the Quick Start shows. A transaction on Mainnet spends real coins and cannot be undone.
Create the server key
The server needs a key for its own wallet.
The server key controls the server wallet and everything it receives. Never share it and never paste it into code. Save it in a .env file as SERVER_PRIVATE_KEY=YOUR_SERVER_KEY and add .env to your .gitignore.
Generate the key once:
node -p "require('@bsv/sdk').PrivateKey.fromRandom().toHex()"Write the server
Create pay-server.ts in your project folder:
import express from 'express'
import { Setup, type SetupEnv } from '@bsv/wallet-toolbox'
import { createPaymentMiddleware } from '@bsv/402-pay/server'
const { wallet } = await Setup.createWalletSQLite({
env: { chain: 'test' } as SetupEnv,
rootKeyHex: process.env.SERVER_PRIVATE_KEY!,
filePath: './server-wallet.sqlite',
databaseName: 'paid-api'
})
const app = express()
app.get('/free', (req, res) => {
res.json({ message: 'Free content' })
})
app.get('/premium', createPaymentMiddleware({ wallet, calculatePrice: () => 1000 }), (req, res) => {
res.json({ message: 'Premium content' })
})
app.listen(3000, () => console.log('Listening on http://localhost:3000'))Start the server and check the price
Start the server:
npx tsx --env-file=.env pay-server.tsA request to /premium with no payment, for example with curl -i http://localhost:3000/premium, gets the price and the identity keyThe public key that identifies a user. Other users send to it of the server in two headers, and an empty body:
HTTP/1.1 402 Payment Required
x-bsv-sats: 1000
x-bsv-server: 03020754b9b31681085c87d054d0039b2f2534b27ce23e541c53bb0aa6e0e7279eWrite the client
In the same project folder, create pay-client.ts:
import { WalletClient } from '@bsv/sdk'
import { create402Fetch } from '@bsv/402-pay/client'
const fetch402 = create402Fetch({ wallet: new WalletClient('auto', 'localhost') })
const response = await fetch402('http://localhost:3000/premium')
console.log(response.status)
if (response.ok) console.log(await response.json())Run it and approve the payment
Run the client:
npx tsx pay-client.tsBSV Desktop opens a spending request for the price plus the network fee. A blockchain transaction cannot be undone once you approve it. The script then prints the status and the answer:
200
{ message: 'Premium content' }If the script prints 402 or 503 instead, the server refused the payment. Check the server log before you run the client again, because each run pays again.
What the key lines do:
Setup.createWalletSQLitebuilds the server wallet on a local SQLite file, withchain: 'test'for testnet.- The second argument of
WalletClientis the originator, the name BSV Desktop shows for your app. Without it, a Node script cannot reach the wallet.
Put the middleware on the route, as in the example. A trailing slash or a different letter case in the path bypasses a single price table keyed by req.path, and the server answers those requests without a payment.
Configuration options
The sections below cover the settings of the middleware and the client, and how a payment is checked.
Settings and defaults
These settings control how a route is priced, which wallet receives the payment and how the client caches what it paid for:
| Option | Default | Effect |
|---|---|---|
calculatePrice | Required | Returns the price in satoshis for a request. 0 or undefined makes the route free |
wallet | Required | A wallet that can receive payments, such as the one from Setup.createWalletSQLite. A ServerWallet from @bsv/simple is not one, so pass serverWallet.getClient() instead |
replayStore | InMemoryPaymentReplayStore | Remembers used payments in this process only, up to 100,000 entries. With several server processes, inject one shared store with a claim(transactionId, expiresAt) method. The method must be atomic and return false for a transaction ID it already holds |
cacheTimeoutMs on create402Fetch | Off | Keeps a paid answer to a GET request per URL for that long, so the next call makes no request and pays nothing. Call clearCache() to force a new payment |
How a payment is checked
A payment is valid for 30 seconds. If a client sends the same payment headers twice, the second request gets a new 402. If the wallet or the replay store fails after the payment started, the server answers 503 with no new price, so the client does not pay twice. The package does not refund that payment. The client refuses a plain http:// address unless it is a loopback address (localhost, 127.0.0.1 or [::1]), so serve a deployed API over HTTPS.
Limitations
Check these two limits before you use the package:
- A
ServerWalletfrom@bsv/simpleneeds a storage server on the same network as its wallet. The default storage is a Mainnet server, so a testnet payment fails withThe tx parameter must be valid AtomicBEEFand the server answers503. SetstorageUrl: 'https://go-wallet-testnet-us-1.bsvblockchain.tech'to accept a testnet payment. It is a hosted server, so check it before you rely on it. The SQLite wallet in the example does not use a hosted server. - For routes that already use BRC-103BSV Request for Comments 103, mutual authentication between two peers authentication, use
@bsv/payment-express-middlewarewith@bsv/auth-express-middleware. That is a different flow.
Related articles
To learn more about paying for APIs on the BSV blockchain, review these articles: