Native L402 Integration — Express (Node.js)
This walkthrough takes you from a vanilla Express app to charging Lightning payments per request in under 10 minutes. You'll install l402-express, add one line of middleware, and your existing endpoints become paid endpoints.
If you haven't picked an integration mode yet, start with the Native Integration overview to understand when Native mode is the right fit.
A complete, working Express integration lives at l402-example-node — clone it, set your API key, and curl a live 402 → pay → 200 flow before wiring your own app.
Prerequisites
- Node.js 18 or higher
- An Express app (4.x or 5.x)
- A Lightning Enable merchant API key, from Dashboard → Settings → API Credentials (any plan, including the Free Producer Sandbox)
- A payment provider (Strike, OpenNode, or an NWC wallet) configured under Dashboard → Settings → Payment Provider
Install
npm install l402-express l402-server
l402-server is the underlying SDK that l402-express calls; both are MIT-licensed and the middleware re-exports the SDK's types so most consumers won't import l402-server directly.
30-second example
import express from "express";
import { l402 } from "l402-express";
const app = express();
// Anything mounted here costs 100 sats per request.
app.use("/api/premium", l402({
apiKey: process.env.LIGHTNING_ENABLE_API_KEY,
priceSats: 100,
}));
app.get("/api/premium/weather", (_req, res) => {
res.json({ temp: 72 });
});
app.listen(3000);
That's the whole integration. The middleware:
- Reads
Authorization: L402 <macaroon>:<preimage>from each request - If absent → mints a fresh challenge via Lightning Enable's hosted producer API and returns
402 Payment Requiredwith the invoice in theWWW-Authenticateheader and a JSON body - If present → verifies the credential via Lightning Enable. On valid → call
next(); on invalid → respond401 Unauthorized
Endpoints NOT mounted under l402(...) pass through untouched. So you can mix paid and free routes freely.
Which route a token unlocks
From l402-express 0.2.0 (which depends on l402-server 0.2.0), the middleware sends the request's resource with every verifyToken call, and the hosted API enforces the macaroon's path caveat. A token bought for one of your routes returns 401 on a different route. By default the middleware verifies against the same value it binds at minting (the resource option when you set it, otherwise req.path), so a token it issued for a route verifies on that route. Merchant binding and expiry are always enforced by the hosted API.
The verifyResource option controls this. Leave it unset for the default above, set it to false to skip enforcement and compare res.locals.l402.resource yourself, or set it to a value or function to verify against a different resource than the one bound at minting.
Two Express details decide what "the same route" means:
-
Mount prefixes. Inside
app.use("/api/premium", l402(...)), Express strips the mount prefix, soreq.pathis mount-relative (/weather, not/api/premium/weather). Two mounts that share a sub-path, such as/api/cheap/weatherand/api/premium/weather, both bind/weather, and a token from one passes on the other. Bind the full path so minting and verification both use it:app.use("/api/premium", l402({
apiKey: KEY,
priceSats: 500,
resource: (req) => req.baseUrl + req.path, // bind the full path
})); -
Price. The middleware doesn't send the price with the verification. If a
priceSatsfunction charges different prices on the same path (for example, by query parameter), a token bought at the lower price also passes at the higher one. Put the price-deciding input intoresource, or compareres.locals.l402.amountSatsin your handler.
l402-express 0.1.x and l402-server 0.1.x call the verify endpoint with only the macaroon and preimage. They don't pass or compare the request path or amount, so a token bought for one of your routes also passes verification on a different route gated under the same API key, within the token's validity window (60 minutes by default). Upgrade to 0.2.0 or later.
If you stay on 0.1.x and gate multiple prices or resources (for example, /api/cheap at 10 sats and /api/premium at 500 sats), compare res.locals.l402.resource against the current request's path in your handler:
router.get("/forecast", l402({ apiKey: KEY, priceSats: 100 }), (req, res) => {
if (res.locals.l402.resource !== req.path) {
return res.status(401).json({ error: "Token was purchased for a different resource" });
}
res.json({ forecast: "7-day data..." });
});
With a mount prefix, bind the full path with resource: (req) => req.baseUrl + req.path as shown above, and compare res.locals.l402.resource against req.baseUrl + req.path.
A single mount with a single flat price is unaffected in practice, because every token you issue is for the same class of access.
What the caller sees
Without payment
curl -i https://your-api.example/api/premium/weather
HTTP/1.1 402 Payment Required
Content-Type: application/json
WWW-Authenticate: L402 macaroon="AgELbWFjYXJvb24...", invoice="lnbc1u1p3..."
{
"error": "Payment Required",
"l402": {
"macaroon": "AgELbWFjYXJvb24...",
"invoice": "lnbc1u1p3...",
"amount_sats": 100,
"payment_hash": "abc123...",
"expires_at": "2026-05-12T01:00:00Z",
"resource": "/api/premium/weather"
}
}
With payment
After paying the Lightning invoice and extracting the preimage:
curl -i https://your-api.example/api/premium/weather \
-H 'Authorization: L402 AgELbWFjYXJvb24...:deadbeef...'
HTTP/1.1 200 OK
Content-Type: application/json
{ "temp": 72 }
Variable per-request pricing
Pass a function instead of a static priceSats to derive the price from the request:
app.use("/api/llm", l402({
apiKey: process.env.LIGHTNING_ENABLE_API_KEY,
priceSats: (req) => req.query.model === "premium" ? 500 : 100,
}));
The function can return a number or a Promise<number>. Use it for tiered pricing, user-based pricing, dynamic cost-of-goods scenarios, etc.
resource and description accept the same function-or-static shape.
Configuration reference
| Option | Type | Default | Notes |
|---|---|---|---|
apiKey | string | required (one of apiKey / client) | Merchant API key |
client | L402Server | — | Pre-constructed SDK client; use to share across mounts |
priceSats | number | (req) => number | Promise<number> | required | Price in satoshis, ≥ 1 |
resource | string | (req) => string | Promise<string> | req.path | Bound as a macaroon caveat |
verifyResource | string | (req) => string | Promise<string> | false | the resource value | 0.2.0 and later. Resource sent with each verification so the hosted API enforces the path caveat. false opts out |
description | string | (req) => string | undefined | none | Shown in the payer's Lightning wallet |
idempotencyKey | (req) => string | undefined | none | Sends X-Idempotency-Key for retry-safe challenge issuance. Without it, each request mints a fresh challenge |
baseUrl | string | https://api.lightningenable.com | Override producer API URL (testing) |
onInvalidToken | (req, res, failure, next) => void | Promise<void> | sends 401 | Custom failure handler — useful for sending a fresh 402 instead |
Accessing the verified credential in your handler
After a successful verification the middleware sets res.locals.l402 so downstream handlers can see what was paid for:
app.get("/api/premium/weather", (_req, res) => {
const { resource, amountSats, paymentHash } = res.locals.l402;
console.log(`Served ${resource} for ${amountSats} sats (${paymentHash})`);
res.json({ temp: 72 });
});
Useful for usage logging, per-endpoint analytics, fraud detection.
Mounting patterns
One price for everything
app.use(l402({ apiKey: KEY, priceSats: 50 }));
// every endpoint below this costs 50 sats
Different prices for different sub-paths
const fullPath = (req) => req.baseUrl + req.path;
app.use("/api/cheap", l402({ apiKey: KEY, priceSats: 10, resource: fullPath }));
app.use("/api/premium", l402({ apiKey: KEY, priceSats: 500, resource: fullPath }));
Binding the full path keeps a token from /api/cheap/... off a matching route under /api/premium/.... See Which route a token unlocks.
Per-route in a Router
import express from "express";
import { l402 } from "l402-express";
const router = express.Router();
router.get("/forecast", l402({ apiKey: KEY, priceSats: 100 }), forecastHandler);
router.get("/historical", l402({ apiKey: KEY, priceSats: 50 }), historyHandler);
router.get("/free-info", freeInfoHandler); // not gated
app.use("/api", router);
Sharing one SDK client across mounts
Each l402(...) call constructs its own internal L402Server instance. For high-throughput apps you may prefer one shared instance with shared HTTP connection pooling:
import { L402Server } from "l402-server";
import { l402 } from "l402-express";
const client = new L402Server({ apiKey: process.env.LIGHTNING_ENABLE_API_KEY });
app.use("/api/cheap", l402({ client, priceSats: 10 }));
app.use("/api/premium", l402({ client, priceSats: 500 }));
Mutually exclusive with apiKey — pass one or the other.
Custom failure handling
By default an invalid L402 token returns 401 Unauthorized. Some merchants prefer to issue a fresh 402 so the caller can retry without having to make a separate request first:
app.use(l402({
apiKey: KEY,
priceSats: 100,
onInvalidToken: async (_req, res, failure, _next) => {
// Send a fresh 402 challenge instead of 401.
// (You'd typically mint a new challenge via the SDK here. Sketch only —
// see the runnable app at
// https://github.com/refined-element/l402-example-node for a complete
// integration.)
res.status(402).json({ error: "Token rejected; please pay again", details: failure.error });
},
}));
When onInvalidToken is supplied, the middleware does NOT send the default 401 — you are responsible for either sending a response or calling next().
Troubleshooting
"Bad Gateway" 502 on every request
The middleware returns 502 whenever the producer API refuses to mint; the message field carries the reason. Common causes:
LIGHTNING_ENABLE_API_KEYis missing or invalid- No payment provider is configured on your account (
payment_provider_not_configured) - A Free Producer Sandbox cap was reached (
plan_endpoint_limit,plan_volume_limit,plan_price_limit) - An outbound firewall blocks
api.lightningenable.com
See the Producer API error table for every code.
Every request returns 402 even after payment
The Authorization header probably isn't reaching your Express app. If you're behind a reverse proxy (nginx, Cloudflare, load balancer), confirm the Authorization header is being forwarded.
Source and license
Both packages are MIT-licensed open source:
Issues, pull requests, and protocol-level discussion at lightninglabs/L402 all welcome.
Next steps
- Producer API reference — full HTTP surface if you ever want to call the underlying API directly
- Native Integration — ASP.NET Core — same flow for .NET
- Proxy setup walkthrough — if you decide Proxy mode is a better fit