Fastify
Learn how to accept your first payment using Fastify and the Sangria TypeScript SDK.
Prerequisites
To get the most out of this guide, you'll need to:
- Create an API key from the Sangria dashboard
- Have Node.js 18+ installed
1. Install
Install the Sangria SDK in your Fastify project.
npm install @sangria-sdk/core2. Initialize the client
Create a Sangria instance with your API key.
import { Sangria } from "@sangria-sdk/core";
const sangria = new Sangria({
apiKey: process.env.SANGRIA_SECRET_KEY,
});3. Register the plugin
Fastify requires a one-time plugin registration before using the payment middleware. This decorates the request object so request.sangria is available in your handlers.
import Fastify from "fastify";
import { sangriaPlugin } from "@sangria-sdk/core/fastify";
const fastify = Fastify();
fastify.register(sangriaPlugin);4. Protect a route
Use fixedPrice as a preHandler hook on any route.
import Fastify from "fastify";
import { Sangria } from "@sangria-sdk/core";
import { sangriaPlugin, fixedPrice } from "@sangria-sdk/core/fastify";
const fastify = Fastify();
const sangria = new Sangria({
apiKey: process.env.SANGRIA_SECRET_KEY,
});
fastify.register(sangriaPlugin);
// This endpoint is free
fastify.get("/", async () => {
return { message: "Hello! This endpoint is free." };
});
// This endpoint costs $0.01 per request
fastify.get(
"/premium",
{
preHandler: fixedPrice(sangria, {
price: 0.01,
description: "Access premium content",
}),
},
async () => {
return { message: "You accessed the premium endpoint!" };
}
);
await fastify.listen({ port: 4002 });5. Run it
Start your server:
SANGRIA_SECRET_KEY=sg_live_xxx node server.jsWhen an agent calls GET /premium:
- First request (no payment) — the SDK returns
402 Payment Requiredwith the price and payment details - Agent signs the USDC payment off-chain
- Retry with payment — the agent sends the signed payment in a
payment-signatureheader - SDK settles the payment on-chain and your handler runs
Try it yourself
# This will return a 402 with payment requirements
curl http://localhost:4002/premium