JavaScript client library for L402 (HTTP 402 Payment Required with Lightning Network) - pay-per-request APIs.
npm install l402L402 is a protocol for pay-per-request APIs using Lightning Network:
- Client makes request
- Server returns HTTP 402 with a Lightning invoice
- Client pays invoice and retries with payment proof
- Server fulfills request
import { fetch } from 'l402';
// Define a wallet that can pay Lightning invoices
const wallet = {
async payInvoice(invoice: string): Promise<string> {
// Use your Lightning wallet (LNbits, LND, Alby, etc.)
const response = await fetch('https://your-wallet/pay', {
method: 'POST',
body: JSON.stringify({ invoice }),
});
return response.json().preimage;
}
};
// Make a paid API request
const result = await fetch('https://api.example.com/paid-endpoint', wallet, {
autoPay: true,
maxSats: 100, // Don't pay more than 100 sats
});
if (result.paid) {
console.log('Paid and received:', result.body);
} else if (result.status === 402) {
console.log('Payment required:', result.challenge);
} else {
console.log('Response:', result.body);
}If you want to handle payment yourself:
import { parseChallenge } from 'l402';
const response = await fetch('https://api.example.com/paid-endpoint');
const body = await response.text();
if (response.status === 402) {
const challenge = parseChallenge(response.status, response.headers, body);
console.log('Invoice:', challenge.invoice);
console.log('Amount:', challenge.amountSats, 'sats');
console.log('Payment hash:', challenge.paymentHash);
}| Option | Type | Default | Description |
|---|---|---|---|
autoPay |
boolean | false | Automatically pay invoices |
maxSats |
number | 1000 | Maximum sats to pay automatically |
allowUnknownAmount |
boolean | false | Allow auto-paying when amount is unknown |
retryBackoff |
number[] | [0, 250, 750, 1500] | Milliseconds to wait between retries |
Implement this interface to use auto-pay:
interface Wallet {
payInvoice(invoice: string): Promise<string>; // Returns preimage
}Try against a real L402 endpoint:
curl -i https://maximumsats.com/api/dvm
# Returns 402 with invoice, then pay and retry with:
# X-Payment-Hash: <payment_hash>MIT