Express

Learn how to accept your first payment using Express and the Sangria TypeScript SDK.

Prerequisites

To get the most out of this guide, you'll need to:

1. Install

Install the Sangria SDK in your Express project.

npm install @sangria-sdk/core

2. Initialize the client

Create a Sangria instance with your API key. Store your key in an environment variable — never hard-code it.

import { Sangria } from "@sangria-sdk/core";

const sangria = new Sangria({
  apiKey: process.env.SANGRIA_SECRET_KEY,
});

3. Protect a route

Import the Express adapter and add fixedPrice as middleware to any route you want to charge for. Set a price in USD and an optional description.

import express from "express";
import { Sangria } from "@sangria-sdk/core";
import { fixedPrice } from "@sangria-sdk/core/express";

const app = express();

const sangria = new Sangria({
  apiKey: process.env.SANGRIA_SECRET_KEY,
});

// This endpoint is free
app.get("/", (_req, res) => {
  res.json({ message: "Hello! This endpoint is free." });
});

// This endpoint costs $0.01 per request
app.get(
  "/premium",
  fixedPrice(sangria, {
    price: 0.01,
    description: "Access premium content",
  }),
  (_req, res) => {
    res.json({ message: "You accessed the premium endpoint!" });
  }
);

app.listen(4001);

4. Run it

Start your server:

SANGRIA_SECRET_KEY=sg_live_xxx node server.js

When an agent calls GET /premium:

  1. First request (no payment) — the SDK returns 402 Payment Required with the price and payment details
  2. Agent signs the USDC payment off-chain
  3. Retry with payment — the agent sends the signed payment in a payment-signature header
  4. SDK settles the payment on-chain and your handler runs

Try it yourself

# This will return a 402 with payment requirements
curl http://localhost:4001/premium

The response includes everything an agent needs to sign and submit payment automatically.

On this page

⭐️