Skip to main content

Overview

The @key0ai/key0/fastify subpath exports two pieces:

Installation

Routes

When you register key0Plugin, the following routes are added to your Fastify instance:

Setup

1

Configure SellerConfig and storage

Create your SellerConfig, payment adapter, challenge store, and seen-tx store. These are framework-agnostic and shared across all integrations.
2

Register the Key0 plugin

Pass the config objects as plugin options to fastify.register.
After registration, GET /.well-known/agent.json returns your agent card.
3

Protect routes with access-token validation

Use fastifyValidateAccessToken as an onRequest hook on any route that requires a paid access token.
The hook reads the Authorization: Bearer <jwt> header, verifies the signature, and attaches the decoded payload to request.key0Token. If verification fails, it short-circuits with a 401 or 500 JSON response.
4

Start the server

Full working example

Accessing the decoded token

The fastifyValidateAccessToken hook attaches the decoded JWT payload to request.key0Token. Because Fastify’s FastifyRequest type does not include this property by default, you need a type assertion to access it:
The payload includes sub (request ID), jti (challenge ID), resourceId, planId, and txHash.

Pay-Per-Request Routes

key0Plugin registers the plugin and exposes a payPerRequest(routeId, opts?) factory on the plugin instance. Use it as a Fastify preHandler hook to gate routes behind micro-payments — no JWT issued, payment settles inline.
Without a PAYMENT-SIGNATURE header the hook returns 402 with x402 payment requirements. After settlement, request.key0Payment contains the PaymentInfo object. For standalone gateway mode, add proxyTo to SellerConfig — see the Express integration for the full proxy configuration reference.

Next Steps

SellerConfig Reference

Complete reference for every configuration option.

Paying for Access

How clients discover, pay, and call your protected endpoints.

Hono Integration

Key0 as a Hono sub-app.

x402 HTTP Flow

Full protocol reference for the payment flow.