WebExtract · Docs · Examples

Minimal examples

Two single-file Node 20+ scripts: a free first call, then a paid one. Save package.json and a script in one folder, run npm install, then node <file>. No wallet? Try it in the browser first: /try. Full reference: /docs.

Use a low-balance wallet you control and never commit its key. MIT-licensed (LICENSE).

Using a coding agent? Paste this

For Cursor, Claude Code, Codex or any agent that can run shell commands. It reads the price and makes a free call; it never touches a wallet or a key.

Make a new empty folder. Download https://webextract.dev/examples/min/package.json and https://webextract.dev/examples/min/rest.mjs into it, then run `npm install`.
Then run `node rest.mjs` (one free call, 20 per day per IP) and `node rest.mjs --pay --dry-run` (reads the x402 price from the 402 response and signs nothing). Show me both outputs.
Do not run `--pay` without `--dry-run`. Do not create, read, ask for or set any wallet key or EVM_PRIVATE_KEY. I will run the paid call myself.

To pay one call, run it yourself in your own terminal with a low-balance wallet: EVM_PRIVATE_KEY=0x... node rest.mjs --pay. Payments above $0.01 are refused.

rest.mjs

// WebExtract REST in one file (Node 20+). Run `npm i` next to package.json, then:
//   node rest.mjs [url]                                     free try: X-Billing: free, 20 calls/day per IP, no key
//   node rest.mjs --pay --dry-run [url]                     read the 402 price, sign nothing (no key needed)
//   EVM_PRIVATE_KEY=0x... node rest.mjs --pay [url]         pay one call ($0.002 USDC on Base) from YOUR wallet
//   WEBEXTRACT_SANDBOX=1 EVM_PRIVATE_KEY=0x... node rest.mjs --pay   Base Sepolia test USDC (faucet.circle.com)
// Use a low-balance wallet you control and never commit its key. Payments above $0.01 are refused.
import { wrapFetchWithPaymentFromConfig } from "@x402/fetch";
import { decodePaymentRequiredHeader } from "@x402/core/http";
import { ExactEvmScheme } from "@x402/evm";
import { privateKeyToAccount } from "viem/accounts";

const BASE = process.env.WEBEXTRACT_BASE || "https://api.webextract.dev";
const SANDBOX = process.env.WEBEXTRACT_SANDBOX === "1", UA = process.env.WEBEXTRACT_UA || "webextract-example-min/1";
const args = process.argv.slice(2), PAY = args.includes("--pay"), DRY = args.includes("--dry-run");
const target = args.find(a => !a.startsWith("--")) || "https://example.com";
const url = `${BASE}${PAY && SANDBOX ? "/sandbox" : ""}/v1/markdown?url=${encodeURIComponent(target)}`;
const NETWORK = SANDBOX ? "eip155:84532" : "eip155:8453"; // Base Sepolia (test USDC) or Base mainnet
const USDC = SANDBOX ? "0x036CbD53842c5426634e7929541eC2318f3dCF7e" : "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913";
const MAX = 10000n; // $0.01 cap per payment (USDC has 6 decimals)
const show = async res => { const b = await res.json(); console.log(res.status, res.ok ? b.markdown?.slice(0, 300) : b); };

if (!PAY) { // (1) free try
  const res = await fetch(url, { headers: { "User-Agent": UA, "X-Billing": "free" } });
  console.log("free calls left today:", res.headers.get("x-free-remaining")); await show(res); process.exit(0);
}
const headers = { "User-Agent": UA, "X-Billing": SANDBOX ? "x402-testnet" : "x402" };
const pick = (_v, reqs) => { const r = reqs.find(r => r.network === NETWORK && BigInt(r.amount) <= MAX); if (!r) throw new Error(`no ${NETWORK} option at or under $0.01`); return r; };
if (DRY) { // (2a) read the 402 and show what would be paid
  const res = await fetch(url, { headers }), pr = res.headers.get("payment-required");
  if (!pr) { await show(res); process.exit(1); }
  try { const r = pick(0, decodePaymentRequiredHeader(pr).accepts); console.log(`HTTP ${res.status}: would pay ${Number(r.amount) / 1e6} USDC on ${r.network} to ${r.payTo} (dry run, nothing signed)`); }
  catch (e) { console.error(e.message); process.exit(1); }
  process.exit(0);
}
if (!process.env.EVM_PRIVATE_KEY) { console.error("set EVM_PRIVATE_KEY (your own wallet) or add --dry-run"); process.exit(1); }
const pay = wrapFetchWithPaymentFromConfig(fetch, { // (2b) sign one option, retry with PAYMENT-SIGNATURE, server settles
  schemes: [{ network: NETWORK, client: new ExactEvmScheme(privateKeyToAccount(process.env.EVM_PRIVATE_KEY)) }],
  paymentRequirementsSelector: pick, spendControls: { allowedAssets: [{ network: NETWORK, asset: USDC, maxAmountPerPayment: String(MAX) }] },
});
const res = await pay(url, { headers });
console.log(res.headers.get("payment-response") ? "paid (PAYMENT-RESPONSE received)" : "no payment settled"); await show(res);

mcp.mjs

// WebExtract over MCP in one file (Node 20+). Run `npm i` next to package.json, then:
//   node mcp.mjs [url]                          free tier: 20 calls/day per IP, no key, no header needed
//   WEBEXTRACT_KEY=<api_key> node mcp.mjs [url]   prepaid credits (sent as Authorization: Bearer); buy at https://webextract.dev/#pricing
// Never commit your key.
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";

const BASE = process.env.WEBEXTRACT_BASE || "https://api.webextract.dev";
const UA = process.env.WEBEXTRACT_UA || "webextract-example-min/1";
const target = process.argv[2] || "https://example.com";
const headers = { "User-Agent": UA };
if (process.env.WEBEXTRACT_KEY) headers.Authorization = `Bearer ${process.env.WEBEXTRACT_KEY}`;

const client = new Client({ name: "webextract-example-min", version: "1.0.0" });
await client.connect(new StreamableHTTPClientTransport(new URL(`${BASE}/mcp`), { requestInit: { headers } })); // initialize
console.log("server:", client.getServerVersion()?.name);

const { tools } = await client.listTools(); // tools/list
console.log("tools:", tools.map(t => t.name).join(", "));

const res = await client.callTool({ name: "page_markdown", arguments: { url: target } }); // tools/call
for (const c of res.content) if (c.type === "text") console.log(c.text.slice(0, 400));
if (res.isError) {
  // Free tier used up: the text has the next step (prepaid key, or an x402 payment challenge).
  console.error("tool returned an error (see text above)"); process.exitCode = 1;
}
await client.close();

package.json

{
  "name": "webextract-min-examples",
  "private": true,
  "type": "module",
  "engines": { "node": ">=20" },
  "scripts": {
    "rest": "node rest.mjs",
    "pay:dry": "node rest.mjs --pay --dry-run",
    "pay": "node rest.mjs --pay",
    "mcp": "node mcp.mjs"
  },
  "dependencies": {
    "@modelcontextprotocol/sdk": "^1.32.2",
    "@x402/core": "^2.28.0",
    "@x402/evm": "^2.28.0",
    "@x402/fetch": "^2.28.0",
    "viem": "^2.57.7"
  }
}

README.md

# WebExtract: minimal examples (Node 20+)

Two single-file examples that go from a free first call to a paid one.

```sh
npm install
node rest.mjs                      # REST, free try: X-Billing: free (20 calls/day per IP, no signup)
node rest.mjs --pay --dry-run      # read the x402 price from the 402 response; signs nothing
EVM_PRIVATE_KEY=0x... node rest.mjs --pay                       # pay one call: $0.002 USDC on Base (eip155:8453)
WEBEXTRACT_SANDBOX=1 EVM_PRIVATE_KEY=0x... node rest.mjs --pay  # same flow with Base Sepolia test USDC (/sandbox)
node mcp.mjs                       # MCP: initialize, tools/list, page_markdown (free tier, no header needed)
WEBEXTRACT_KEY=<api_key> node mcp.mjs   # MCP with a prepaid key (Authorization: Bearer)
```

- `rest.mjs` pays from your own wallet only. Use a low-balance wallet you control and never commit its key. Any payment above $0.01 is refused (per-payment cap).
- Test USDC for the sandbox: https://faucet.circle.com (Base Sepolia).
- Prepaid credits by card: https://webextract.dev/#pricing (the API key is shown once after payment).
- Optional env: `WEBEXTRACT_BASE` (default `https://api.webextract.dev`), `WEBEXTRACT_UA` (User-Agent, default `webextract-example-min/1`).
- REST errors are JSON and not charged. Full reference: https://webextract.dev/docs

MIT licensed, see https://webextract.dev/examples/LICENSE.txt