Skip to content

Configuration Reference

tollbooth is configured via a single tollbooth.config.yaml file. All fields are documented below.

tollbooth.config.yaml
gateway:
port: 3000
discovery: true
trustProxy: true
cors:
allowedOrigins: ["https://app.example.com"]
wallets:
base: "0xYourBaseWallet"
solana: "YourSolanaWallet"
accepts:
- asset: USDC
network: base
- asset: USDC
network: solana
defaults:
price: "$0.001"
timeout: 60
rateLimit:
requests: 100
window: 1m
facilitator: https://x402.org/facilitator
upstreams:
anthropic:
url: "https://api.anthropic.com"
headers:
x-api-key: "${ANTHROPIC_API_KEY}"
anthropic-version: "2023-06-01"
openai:
url: "https://api.openai.com"
headers:
authorization: "Bearer ${OPENAI_API_KEY}"
routes:
"POST /ai/claude":
upstream: anthropic
path: "/v1/messages"
settlement: after-response
match:
- where: { body.model: "claude-haiku-*" }
price: "$0.005"
- where: { body.model: "claude-sonnet-*" }
price: "$0.015"
- where: { body.model: "claude-opus-*" }
price: "$0.075"
fallback: "$0.015"
"POST /v1/chat/completions":
upstream: openai
type: token-based
models:
gpt-4o: "$0.05"
gpt-4o-mini: "$0.005"
hooks:
onSettled: "hooks/log-payment.ts"
onError: "hooks/handle-error.ts"

Top-level server configuration.

FieldTypeDefaultDescription
portnumber3000Port the gateway listens on
discoverybooleantrueExpose /.well-known/x402 and /.well-known/openapi.json discovery endpoints
hostnamestring—Optional hostname to bind to
corsCorsConfig— (CORS off)Enable CORS headers. allowedOrigins is required. Optional: allowedMethods, allowedHeaders, exposedHeaders, credentials (default false; "*" origin not allowed with credentials), maxAge. See Security & Hardening
trustProxyboolean | number | { hops?, cidrs? }falseTrust X-Forwarded-For / X-Forwarded-Proto from a reverse proxy: true, a number of trusted hops, or specific CIDRs. Enable when running behind Nginx, Caddy, or a cloud load balancer
metrics{ enabled?, path? }{ enabled: false, path: "/metrics" }Expose a Prometheus-compatible metrics endpoint
gateway:
port: 8080
discovery: true
trustProxy: true
cors:
allowedOrigins: ["https://app.example.com"]
metrics:
enabled: true

Maps network names to your wallet addresses. These are the addresses that receive payments.

FieldTypeDescription
<network>stringWallet address for the given network
wallets:
base: "0xYourBaseWallet"
base-sepolia: "0xYourTestnetWallet"
solana: "YourSolanaWallet"

The network names must match the networks in your accepts array.


Array of payment methods the gateway accepts. Each entry specifies an asset and network combination.

FieldTypeDescription
assetstringToken symbol (e.g. USDC)
networkstringNetwork name (e.g. base, base-sepolia, solana)
accepts:
- asset: USDC
network: base
- asset: USDC
network: solana

Routes can override accepted payments with a route-level accepts field.


Default values applied to all routes unless overridden.

FieldTypeDefaultDescription
pricestring—Default price for routes without an explicit price (e.g. "$0.001")
timeoutnumber60Default payment timeout in seconds
rateLimitRateLimitConfig—Default rate-limit applied to all routes. Override per-route with routes.<route>.rateLimit
defaults:
price: "$0.001"
timeout: 60
rateLimit:
requests: 100
window: 1m

RateLimitConfig fields:

FieldTypeDescription
requestsnumberMaximum requests per window (positive integer)
windowstringWindow duration, e.g. "30s", "1m", "1h", "1d"

Prices are specified as dollar strings. "$0.01" = 10,000 USDC micro-units (6 decimals).


URL of the x402 facilitator service that verifies and settles payments.

FieldTypeDefault
facilitatorstringhttps://x402.org/facilitator
facilitator: https://custom-facilitator.example.com

Can be overridden per-route. Route-level facilitator takes precedence over this top-level setting. If neither is specified, defaults to https://x402.org/facilitator.


Configures the settlement strategy used to verify and collect payments. When omitted, tollbooth uses the facilitator strategy by default.

FieldTypeDefaultDescription
strategy"facilitator" | "nanopayments" | "mpp" | "tempo" | "custom""facilitator"Which settlement strategy to use
network"testnet" | "mainnet""testnet"Circle Gateway environment (nanopayments only)
urlstring—Gateway URL override (nanopayments), facilitator URL (mpp, tempo)
methodsMppMethod[]—Payment methods (mpp only, at least one)
tempoTempoConfig—Tempo settings (tempo only)
modulestring—Path to a custom strategy module (custom only)
# No settlement block needed — facilitator is the default.
# Equivalent to:
settlement:
strategy: facilitator

Uses Circle’s Nanopayments Gateway for gas-free, batched USDC settlement. Ideal for sub-cent micropayments and high-frequency use cases.

settlement:
strategy: nanopayments
network: testnet # "testnet" (default) or "mainnet"

Or with a custom gateway URL:

settlement:
strategy: nanopayments
url: https://my-gateway.example.com

Accept stablecoins and Stripe card payments through the Machine Payments Protocol.

settlement:
strategy: mpp
methods:
- type: tempo # stablecoins via the x402 facilitator
- type: stripe # card payments
secretKey: "${STRIPE_SECRET_KEY}"
Method fieldTypeDescription
type"tempo" | "stripe"Payment method
secretKeystringStripe secret key (stripe only, required)

When running more than one instance with the stripe method, set stores.verificationCache.backend: redis so used PaymentIntents are shared across instances. See MPP.

Settle on Tempo with attribution and invoice memos. See Tempo Settlement.

settlement:
strategy: tempo
tempo:
url: "${TEMPO_FACILITATOR_URL}"
recipient: "0xYourMerchantAddress"
network: mainnet
token: pathUSD
recurring:
interval: monthly
autoPay: false
memo:
invoice_id: "{customer_id}-{period}"

TempoConfig fields:

FieldTypeDefaultDescription
urlstringsettlement.urlRequired (here or as settlement.url). x402 facilitator that supports Tempo
recipientstringrequiredMerchant address for attribution and memos. Should match your wallets address
network"mainnet" | "testnet""mainnet"Label for attribution and memos
tokenstring"pathUSD"Label for attribution and memos
recurring.interval"daily" | "weekly" | "monthly" | "yearly"—Plan label ({period} placeholder)
recurring.autoPaybooleanfalseRecorded in attribution. tollbooth doesn’t pull funds automatically
memoRecord<string, string>—Memo templates. Placeholders: {customerId}, {customer_id}, {payer}, {period}, {recipient}, {network}, {token}

Point to your own SettlementStrategy implementation:

settlement:
strategy: custom
module: "./settlement/my-strategy.ts"

See Settlement Strategies for details on each strategy.


Named upstream API configurations. Each upstream defines where requests are proxied to.

FieldTypeDefaultDescription
urlstringrequiredBase URL of the upstream API
headersRecord<string, string>—Headers to inject into proxied requests
timeoutnumber—Request timeout in seconds for this upstream
openapistring—URL or file path to an OpenAPI spec. Routes are auto-imported at startup. See OpenAPI integration
defaultPricestring—Default price applied to auto-imported routes (e.g. "$0.01"). Optional — when omitted, imported routes use defaults.price
upstreams:
anthropic:
url: "https://api.anthropic.com"
headers:
x-api-key: "${ANTHROPIC_API_KEY}"
anthropic-version: "2023-06-01"
timeout: 120
dune:
url: "https://api.dune.com/api"
headers:
x-dune-api-key: "${DUNE_API_KEY}"
myapi:
url: "https://api.example.com"
openapi: "https://api.example.com/openapi.json" # auto-import routes at startup
defaultPrice: "$0.01" # applied to all imported routes

Header values support ${ENV_VAR} syntax. Variables are resolved from process.env at startup. This keeps secrets out of your config file.

headers:
authorization: "Bearer ${API_KEY}"

The core of your config. Maps public-facing routes to upstream APIs with pricing.

Route keys use the format "METHOD /path":

routes:
"GET /weather":
upstream: myapi
price: "$0.01"
"POST /ai/claude":
upstream: anthropic
path: "/v1/messages"
price: "$0.015"
"GET /data/:query_id":
upstream: dune
path: "/v1/query/${params.query_id}/results"
price: "$0.05"
FieldTypeDefaultDescription
upstreamstringrequiredName of the upstream (must match a key in upstreams)
pathstringsame as route pathPath to forward to on the upstream. Supports ${params.*} interpolation
pricestring | { fn: string }from defaults.priceStatic price or path to a custom pricing function
matchMatchRule[]—Array of conditional pricing rules (evaluated top-to-bottom)
fallbackstringfrom defaults.pricePrice when no match rule matches
acceptsAcceptedPayment[]from top-level acceptsOverride accepted payments for this route
payTostring | PayToSplit[]from walletsOverride payment recipient or configure split payments
hooksRouteHooksConfig—Per-route lifecycle hooks (override global hooks)
metadataRecord<string, unknown>—Arbitrary metadata included in discovery responses
facilitatorstringfrom top-level facilitatorOverride the facilitator URL for this route
settlement"before-response" | "after-response""before-response"When to settle payment relative to the upstream request. See Refund Protection
rateLimitRateLimitConfigfrom defaults.rateLimitOverride rate-limit for this route
verificationCacheVerificationCacheConfig—Cache payment verification results to reduce facilitator calls on repeated payments (facilitator strategy only)
pricingRoutePricingConfig—Pricing model (model, duration) plus price / match / fallback. See Time-based pricing

Set price: "$0" to bypass the x402 payment flow entirely. The route acts as a transparent proxy — no 402 response, no payment required.

routes:
"GET /health":
upstream: myapi
price: "$0" # free — proxied directly, no payment
"GET /data":
upstream: myapi
price: "$0.01" # paid — requires x402 payment

This is useful for health checks, public listings, or mixed free/paid APIs where some endpoints should be openly accessible.

Charge once for a period of access instead of per request. The simplest way is a period suffix on the route price:

routes:
"GET /premium/*":
upstream: myapi
price: "$10/month" # pay once, access for 30 days

This is shorthand for:

routes:
"GET /premium/*":
upstream: myapi
pricing:
model: time
duration: 30d
price: "$10"

The first paid request settles and starts a session for that payer on that route. Until the session expires, requests carrying a valid payment header from the same payer are let through without another charge. After it expires, the route returns 402 and the client pays again. Nothing renews automatically.

Supported suffixes (case-insensitive):

SuffixDuration
/request, /reqPer request (same as no suffix)
/second, /sec, /s1 second
/minute, /min, /m1 minute
/hour, /hr, /h1 hour
/day, /daily, /d1 day
/week, /weekly, /w7 days
/month, /monthly, /mo30 days
/year, /yearly, /yr, /y365 days

Rules:

  • An unknown suffix (e.g. "$10/fortnight") is a config error, and the gateway won’t start.
  • An explicit pricing.model or pricing.duration takes precedence over the suffix.
  • The suffix changes the pricing model only on a route’s price or pricing.price. In match rules, fallback and defaults.price, only the amount is used.
  • pricing.model: time without a suffix requires pricing.duration (e.g. "12h", "7d").

Sessions are stored in the time-session store: in memory by default, and reset on restart. Use stores.timeSession.backend: redis when running more than one instance. See stores.

Route paths support Express-style parameters with :param syntax:

routes:
"GET /data/:query_id":
upstream: dune
path: "/v1/query/${params.query_id}/results"
price: "$0.05"

GET /data/12345 → proxied to https://api.dune.com/api/v1/query/12345/results

Use * as a catch-all wildcard that matches the rest of the path. Access the matched value with params["*"]:

routes:
"GET /articles/*":
upstream: blog
price:
fn: "./pricing/article-price.ts"

The path field lets your public API shape differ from the upstream:

routes:
"POST /ai/claude":
upstream: anthropic
path: "/v1/messages" # upstream path differs from public path
price: "$0.015"

For proxying OpenAI-compatible APIs (OpenAI, OpenRouter, LiteLLM, Ollama, etc.), set type: token-based to enable automatic model-based pricing without writing match rules. openai-compatible is also accepted as an alias.

The gateway auto-extracts the model field from the JSON request body and prices the request using a built-in table of common models (GPT-4o, Claude, Gemini, Llama, Mistral, DeepSeek, etc.).

upstreams:
openai:
url: "https://api.openai.com/"
headers:
authorization: "Bearer ${OPENAI_API_KEY}"
routes:
"POST /v1/chat/completions":
upstream: openai
type: token-based
"POST /v1/completions":
upstream: openai
type: token-based

Add a models map to set custom prices or add models not in the default table:

routes:
"POST /v1/chat/completions":
upstream: openai
type: token-based
models:
gpt-4o: "$0.05" # override default
gpt-4o-mini: "$0.005" # override default
my-fine-tune: "$0.02" # custom model
fallback: "$0.01" # price for models not in any table

When pricing a token-based request, the gateway checks:

  1. models (your route overrides) — exact match
  2. Built-in default table — exact match
  3. price / fallback / defaults.price — standard fallback chain

Streaming responses (SSE) work out of the box — the gateway preserves the ReadableStream without buffering.


Conditional pricing rules evaluated on each request. Rules are checked top-to-bottom; the first match wins.

FieldTypeDescription
whereRecord<string, string | number | boolean>Conditions to match against the request
pricestringPrice to charge when this rule matches
payTostring | PayToSplit[]Optional payment recipient override for this rule

The where object matches against request properties:

PrefixSourceExample
body.*JSON request bodybody.model: "claude-opus-*"
query.*URL query parametersquery.tier: "premium"
headers.*Request headersheaders.x-priority: "high"
params.*Path parametersparams.query_id: "123*"

Values support glob patterns for flexible matching:

match:
- where: { body.model: "claude-haiku-*" }
price: "$0.005"
- where: { body.model: "claude-sonnet-*" }
price: "$0.015"
- where: { body.model: "claude-opus-*" }
price: "$0.075"
fallback: "$0.015"

Lifecycle hooks let you run custom code at key points in the request lifecycle. Hooks can be defined globally or per-route.

hooks:
onRequest: "hooks/on-request.ts"
onPriceResolved: "hooks/log-price.ts"
onSettled: "hooks/log-payment.ts"
onResponse: "hooks/track-usage.ts"
onError: "hooks/handle-error.ts"

Route-level hooks override global hooks for that route:

routes:
"POST /ai/claude":
upstream: anthropic
price: "$0.015"
hooks:
onResponse: "hooks/track-claude-usage.ts"
HookWhenSignatureUse case
onRequestBefore anything(ctx: RequestHookContext) => Promise<HookResult | undefined>Block abusers, rate limit
onPriceResolvedAfter price is calculated(ctx: HookContext) => Promise<HookResult | undefined>Override or log pricing
onSettledAfter payment confirmed(ctx: SettledHookContext) => Promise<HookResult | undefined>Log payments to DB
onResponseAfter upstream responds(ctx: ResponseHookContext) => Promise<UpstreamResponse | undefined>Transform response, track usage
onErrorWhen upstream fails(ctx: ErrorHookContext) => Promise<void>Trigger refunds

Hooks that return HookResult can short-circuit the request:

hooks/on-request.ts
export default async (ctx) => {
if (isBlocked(ctx.req.headers['x-forwarded-for'])) {
return { reject: true, status: 403, body: 'Blocked' };
}
// return undefined to continue normally
};

The onResponse hook can return a modified UpstreamResponse to transform the response before it’s sent to the client.


Prices are specified as dollar strings and converted to USDC micro-units (6 decimal places):

Dollar stringUSDC micro-unitsActual USDC
"$0"0Free — skips x402 payment flow
"$0.001"1,0000.001 USDC
"$0.01"10,0000.01 USDC
"$0.05"50,0000.05 USDC
"$1.00"1,000,0001.00 USDC

A route price can also carry a period suffix, e.g. "$10/month", to make the route time-based. See Time-based pricing.


Optional external store configuration for sharing state across gateway instances.

FieldTypeDescription
redisRedisConfigShared Redis connection: url (required), prefix, options
rateLimitStoreSelectionRate-limit counters
verificationCacheStoreSelectionVerification cache, plus used MPP Stripe PaymentIntents
timeSessionStoreSelectionTime-based pricing sessions

StoreSelection fields: backend ("memory" default, or "redis") and an optional redis block (url, prefix, options) that overrides the shared connection for that store.

Each store uses Redis only when its backend is "redis". Setting stores.redis alone doesn’t switch any store over.

stores:
redis:
url: "redis://localhost:6379"
prefix: "tollbooth"
rateLimit:
backend: redis
verificationCache:
backend: redis
timeSession:
backend: redis

When no store is configured, all state is kept in-memory and resets on restart. See Scaling and Shared Stores.


Any string value in the config supports ${ENV_VAR} interpolation:

wallets:
base-sepolia: "${GATEWAY_ADDRESS}"
upstreams:
myapi:
url: "https://api.example.com"
headers:
authorization: "Bearer ${API_KEY}"

Variables are resolved from process.env at config load time. Use a .env file or pass them directly.


Next: CLI Reference →