l402-requests
July 17, 2026 · View on GitHub
Three lines of TypeScript. Paid APIs just work.
import { get } from 'l402-requests';
const response = await get("https://api.example.com/paid-resource");
console.log(await response.json());
That's the entire integration. No payment logic. No invoice parsing. No retry code. No protocol knowledge required.
Behind the scenes, l402-requests detects the 402 challenge, pays the Lightning invoice from your wallet, caches the credential, and retries the request. You get back a normal Response. The API just worked — and it got paid.
Install
npm install l402-requests
Set one environment variable for your wallet and you're done:
export STRIKE_API_KEY="your-strike-api-key"
That's it. Every L402-protected API you call will automatically get paid.
How It Works
Your Code l402-requests L402 Server Lightning
───────── ───────────── ─────────── ─────────
│ │ │ │
│── GET /resource ──▶│ │ │
│ │── GET /resource ───────▶│ │
│ │◀── 402 + invoice + mac ─│ │
│ │ │ │
│ │ check budget │ │
│ │ extract amount │ │
│ │ │ │
│ │── pay invoice ──────────────────────────────▶│
│ │◀── preimage ────────────────────────────────│
│ │ │ │
│ │── GET /resource ────────▶│ │
│ │ Authorization: L402 │ │
│ │◀──── 200 + data ────────│ │
│◀── 200 + data ─────│ │ │
- You make an HTTP request —
get(url) - If the server returns 200, the response comes back as-is
- If the server returns 402 with an L402 challenge:
- The invoice is parsed automatically
- The amount is checked against your budget
- The invoice is paid via your Lightning wallet
- The request is retried with
Authorization: L402 {macaroon}:{preimage}
- Credentials are cached — subsequent requests to the same endpoint don't re-pay
Wallet Configuration
Set environment variables for your wallet. The library auto-detects in priority order:
| Priority | Wallet | Environment Variables | Preimage | Notes |
|---|---|---|---|---|
| 1 | LND | LND_REST_HOST + LND_MACAROON_HEX | Yes | Requires running a node |
| 2 | NWC | NWC_CONNECTION_STRING | Yes | CoinOS, CLINK, Alby Hub compatible |
| 3 | Strike | STRIKE_API_KEY | Yes | No infrastructure required |
| 4 | OpenNode | OPENNODE_API_KEY | No | Cannot be used for L402 — every 402 throws UnsupportedWalletError |
Recommended: Strike — Full preimage support and requires no infrastructure. Set
STRIKE_API_KEYand you're done.
OpenNode does not work with L402. It returns no payment preimage, and L402 needs the preimage to build the
Authorizationheader — a payment would settle and still buy no access. The client refuses before any funds move. OpenNode is still auto-detected, so anOPENNODE_API_KEY-only setup resolves to a wallet that rejects every request; use Strike, LND, or a compatible NWC wallet instead.
NWC (Nostr Wallet Connect)
NWC requires optional peer dependencies:
npm install "@noble/secp256k1@^1.7.1" ws
export NWC_CONNECTION_STRING="nostr+walletconnect://pubkey?relay=wss://relay&secret=hex"
Encryption (NIP-04 / NIP-44 v2): by default the client auto-detects the wallet's
supported encryption from its NIP-47 INFO event (kind 13194) and uses NIP-44 v2 when
advertised (required by Alby Hub), otherwise NIP-04 (CoinOS, CLINK, Primal). If a
wallet doesn't publish an INFO event you can pin the scheme with
NWC_ENCRYPTION=nip44_v2 (or nip04); the default is auto. A wrong scheme surfaces
as a payment timeout because the wallet silently drops requests it can't decrypt.
Explicit Wallet
import { L402Client, StrikeWallet } from 'l402-requests';
const client = new L402Client({
wallet: new StrikeWallet("your-key"),
});
const response = await client.get("https://api.example.com/paid-resource");
Budget Controls
Safety is built in. Budgets are enabled by default so you can't accidentally overspend:
import { L402Client, BudgetController } from 'l402-requests';
const client = new L402Client({
budget: new BudgetController({
maxSatsPerRequest: 500, // Max per single payment (default: 1,000)
maxSatsPerHour: 5000, // Hourly rolling limit (default: 10,000)
maxSatsPerDay: 25000, // Daily rolling limit (default: 50,000)
allowedDomains: new Set(["api.example.com"]),
}),
});
If a payment would exceed any limit, BudgetExceededError is thrown before the payment is attempted — no sats leave your wallet.
To disable budgets entirely:
const client = new L402Client({ budget: null }); // Not recommended
Default Limits
| Limit | Default | Description |
|---|---|---|
maxSatsPerRequest | 1,000 sats | Rejects any single invoice above this |
maxSatsPerHour | 10,000 sats | Rolling 1-hour window |
maxSatsPerDay | 50,000 sats | Rolling 24-hour window |
Spending Introspection
Track every payment made during a session:
const client = new L402Client();
await client.get("https://api.example.com/data");
await client.get("https://api.example.com/more-data");
console.log(`Total: ${client.spendingLog.totalSpent()} sats`);
console.log(`Last hour: ${client.spendingLog.spentLastHour()} sats`);
console.log(`Today: ${client.spendingLog.spentToday()} sats`);
console.log(`By domain:`, client.spendingLog.byDomain());
console.log(client.spendingLog.toJSON());
Two-Step L402 Flows (Commerce)
Some servers intentionally use a two-step L402 flow where payment and claim are separate endpoints. This is common for physical goods — it separates payment from fulfillment and allows the claim URL to be shared with a gift recipient.
For example, the Lightning Enable Store returns a 402 on POST /checkout, and after payment you claim the order at POST /claim with the L402 credential.
In these cases, l402-requests pays the invoice automatically. Retrieve the credential (macaroon + preimage) from the spending log, then make the claim request:
import { L402Client, BudgetController } from 'l402-requests';
const client = new L402Client({
// Store products cost ~48,000 sats incl. shipping — raise the hourly/daily
// caps too, or the default 10k/hour budget rejects the purchase.
budget: new BudgetController({ maxSatsPerRequest: 50000, maxSatsPerHour: 50000, maxSatsPerDay: 100000 }),
});
const checkout = await client.post("https://store.lightningenable.com/api/store/checkout", {
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ items: [{ productId: 2, quantity: 1, size: "L", color: "Black" }] }),
});
// Payment was made — retrieve the credential from the spending log
const record = client.spendingLog.records.at(-1)!;
console.log(`Paid ${record.amountSats} sats`);
// Claim the order with the L402 credential
const claim = await fetch("https://store.lightningenable.com/api/store/claim", {
method: "POST",
headers: {
"Authorization": `L402 ${record.macaroon}:${record.preimage}`,
"Content-Type": "application/json",
},
body: JSON.stringify(claimDetails), // shipping details etc. — see the store's API docs
});
Error Handling
import {
L402Client,
BudgetExceededError,
InvoiceAmountUnknownError,
UnsupportedWalletError,
PaymentFailedError,
NoWalletError,
} from 'l402-requests';
const client = new L402Client();
try {
const response = await client.get("https://api.example.com/paid-resource");
} catch (e) {
if (e instanceof BudgetExceededError) {
console.log(`Over budget: ${e.limitType} limit is ${e.limitSats} sats`);
} else if (e instanceof InvoiceAmountUnknownError) {
console.log(`Refused unpriceable invoice: ${e.reason}`);
} else if (e instanceof UnsupportedWalletError) {
console.log(`Wallet unusable for L402: ${e.walletReason}`);
} else if (e instanceof PaymentFailedError) {
console.log(`Payment failed: ${e.reason}`);
} else if (e instanceof NoWalletError) {
console.log("No wallet configured");
} else {
throw e; // don't swallow what you didn't recognise
}
}
| Exception | When | Funds moved |
|---|---|---|
BudgetExceededError | Payment would exceed a budget limit | No |
InvoiceAmountUnknownError | Invoice amount could not be determined, so it could not be checked against your budget | No |
UnsupportedWalletError | Configured wallet cannot return preimages (OpenNode) | No |
PaymentFailedError | Lightning payment failed (routing, timeout, etc.) | Maybe |
InvoiceExpiredError | Invoice expired before payment | No |
NoWalletError | No wallet env vars detected | No |
DomainNotAllowedError | Domain not in allowedDomains | No |
ChallengeParseError | Malformed L402 challenge header | No |
Every error above extends L402Error, so e instanceof L402Error catches the lot.
InvoiceAmountUnknownError (new in 0.6.0) and UnsupportedWalletError are precondition failures thrown before any payment is attempted, so neither extends PaymentFailedError. An instanceof chain with no branch for them — like this example before 0.6.0 — swallows them silently instead of reporting them. That is why the example now ends in throw e.
Also Available
- Python:
l402-requests— same "three lines of code" experience for Python - .NET:
L402Requests— same experience for .NET
Example: MaximumSats API
MaximumSats provides paid Lightning Network APIs including AI DVM, WoT reports, Nostr analysis, and more. Use l402-requests to automatically pay for these endpoints:
import { get } from 'l402-requests';
const response = await get("https://maximumsats.com/api/dvm");
const data = await response.json();
Set your wallet via environment variable:
export STRIKE_API_KEY="your-strike-api-key"
The library automatically handles the L402 payment protocol — you just get the data.
Source Code
GitHub Repository (MIT License)
Part of the Lightning Enable Ecosystem
l402-requests is the consumer-side complement to the Lightning Enable MCP Server. While the MCP server gives AI agents wallet tools, l402-requests lets your TypeScript code access paid APIs without any agent framework.
Part of Lightning Enable — infrastructure for agent commerce over Lightning. See the full ecosystem.