Skip to main content
Use Express when you want the shortest server-side path to 4Mica. The @4mica/x402 package ships Express middleware that handles HTTP 402 responses, guarantee verification, and settlement for protected routes.

Prerequisites

  • Node.js 18 or later.
  • An Express app.
  • A seller wallet address that receives payments.
  • A buyer wallet with 4Mica collateral if you want to test the paid client.

Install

npm install express @4mica/x402 @x402/fetch viem

Create wallet

Create one wallet for the buyer client and one seller address for payTo. For wallet setup, see Wallet. Keep the buyer private key in an environment variable:
PRIVATE_KEY=0xYourPrivateKey
PAY_TO=0xYourSellerAddress
Use the private key only for buyer-side signing. Use PAY_TO as the seller address advertised by protected routes.

Deposit collateral

Deposit collateral for the buyer wallet before it calls the protected route. Use Base Sepolia (eip155:84532) while you test, then wait for the deposit to finalize. To learn more about collateral setup, see Deposits and Withdrawals.

Protect a route

import express from "express";
import { paymentMiddlewareFromConfig } from "@4mica/x402/server/express";

const app = express();
app.use(express.json());

app.use(
  paymentMiddlewareFromConfig({
    "GET /premium-content": {
      accepts: {
        scheme: "4mica-credit",
        price: "$0.10",
        network: "eip155:84532",
        payTo: process.env.PAY_TO ?? "0xYourAddress",
      },
      description: "Access to premium content",
    },
  }),
);

app.get("/premium-content", (req, res) => {
  res.json({ message: "This is premium content behind a paywall" });
});

app.listen(3030, () => {
  console.log("Server running on http://localhost:3030");
});

Support payment

import { wrapFetchWithPaymentFromConfig } from "@x402/fetch";
import { FourMicaEvmScheme } from "@4mica/x402/client";
import { privateKeyToAccount } from "viem/accounts";

const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`);
const scheme = await FourMicaEvmScheme.create(account);

const fetchWithPayment = wrapFetchWithPaymentFromConfig(fetch, {
  schemes: [{ network: "eip155:84532", client: scheme }],
});

const response = await fetchWithPayment("http://localhost:3030/premium-content");
const data = await response.json();

console.log(data);

What happens

  1. The buyer requests /premium-content without payment.
  2. Express returns HTTP 402 with payment requirements.
  3. The wrapper creates a unique request ID, signs a guarantee, and retries with a payment header.
  4. The middleware verifies and settles the payment before your handler serves the response.