nestjs-x402
v1.3.3
Published
x402 support for NestJS
Maintainers
Readme
NestJS x402 Integration
Seamlessly integrate the x402 payment processing system into your NestJS applications with this library. Designed for developers who want to leverage the power of x402 while maintaining the structure and scalability of NestJS.
Installation
npm install nestjs-x402⚠️ Warning
This library is in early development and is not yet stable.
- Breaking changes may occur frequently without notice
- APIs and interfaces are subject to change
- Not recommended for production use at this time
- Use at your own risk
We recommend waiting for a stable release before using this library in production applications.
Usage
Module registering
The X402Module needs to be registered to use the X402PaymentService, X402Interceptor, and enable functionality of X402 payment processing.
// src/app.module.ts
import { X402Module } from 'nestjs-x402';
import { facilitator } from '@coinbase/x402';
...
@Module({
imports: [
X402Module.register({
global: true, // optional: export providers globally
x402Version: 1,
resource: 'https://example.com/my-digital-resource',
recipients: [{ payTo: '0x8bf15b7c1888d0082c045bdeeb038ccab78d5231', network: 'base' }],
facilitator,
}),
],
...
})
export class AppModule {}Module registering asynchronously
If your facilitator or recipients are loaded from a config service, use registerAsync:
X402Module.registerAsync({
global: true,
useFactory: async () => ({
x402Version: 1,
resource: process.env.X402_RESOURCE!,
recipients: [{ payTo: process.env.PAYTO_BASE!, network: 'base' }],
facilitator: {
/* your facilitator config */
},
}),
inject: [],
});Static pricing
When pricing is known at design time, decorate your route with @X402ApiOptions and provide apiPrices.
The X402Interceptor will generate exact payment requirements and require clients to include a valid X-PAYMENT header.
Protect a route with static pricing:
// src/app.controller.ts
import { X402ApiOptions, X402Interceptor } from 'nestjs-x402';
...
@Controller()
export class AppController {
@Get('greeting')
@X402ApiOptions({
apiPrices: [{ price: '$0.001', network: 'base' }],
description: 'Get a warm greeting',
})
@UseInterceptors(X402Interceptor)
getGreeting() {
return { message: 'Hello — you paid!' };
}
}Notes:
- Clients must include an
X-PAYMENTheader (the signed x402 payment header). Without it the endpoint returns HTTP 402 and anacceptslist describing valid payment requirements. - You can apply the interceptor globally via
APP_INTERCEPTORif you prefer not to decorate every route. The interceptor will ignore route without the@X402ApiOptionsdecorator.
Dynamic pricing
When the price depends on request details (quantity, content size, user tier, etc.), mark the route with isDynamicPricing: true and throw X402DynamicPricing from your handler with computed PricingRequirement[].
The interceptor will catch it and return a 402 response containing the dynamic accepts list.
Example dynamic-pricing handler:
// src/app.controller.ts
import { X402ApiOptions, X402Interceptor } from 'nestjs-x402';
...
@Controller()
export class AppController {
@Get('greeting')
@X402ApiOptions({
description: 'Get a warm greeting',
isDynamicPricing: true,
inputSchema: {
number_of_greetings: {
type: 'number',
description: 'Number of greetings to receive',
},
},
})
@UseInterceptors(X402Interceptor)
async getGreeting(
@Request() req: ExpressRequest,
@Query() { number_of_greetings = 1 },
@X402ReqConfig() x402Config: X402ApiConfig, // injected per-request x402 config
) {
const prices: PricingRequirement[] = [
{ price: `$${1 * Number(number_of_greetings)}`, network: 'base' },
];
const paymentHeader = req.header('X-PAYMENT');
if (!paymentHeader) {
throw new X402DynamicPricing({ dynamicPrices: prices });
}
const paymentRequirements = this.paymentService.getExactPaymentRequirements(
x402Config,
prices,
);
const { valid, x402Response } = await this.paymentService.processPayment({
paymentRequirements,
paymentHeader,
});
if (!valid) {
throw new HttpException(x402Response!, 402);
}
}
}Flow summary:
- Client requests the route without an
X-PAYMENTheader. - Your handler computes prices and throws
X402DynamicPricingwithPricingRequirement[]. X402Interceptorreturns HTTP 402 withacceptsderived from the dynamic prices.- Client builds a valid
X-PAYMENTheader (using x402 client libraries) and retries; interceptor validates and settles the payment, then the handler is allowed to proceed.
Try it locally (example project)
This repository includes a simple example under examples/simple you can run:
cd examples/simple
pnpm install # or npm install
pnpm start:dev # or npm run start:devTesting:
- Call the protected route without
X-PAYMENTto receive HTTP 402 and theacceptslist. - Use the upstream
@coinbase/x402or other x402 client tools to construct a validX-PAYMENTheader and call the endpoint again to complete the payment flow.
Motivation
- The x402 payment processing system is a powerful and flexible solution for handling payments in agent-based applications.
- NestJS is a production-ready framework for backend development but lacks built-in support for x402.
- Existing x402 support is limited to Express.js, leaving a gap for NestJS developers.
- This library bridges that gap by providing decorators and utilities to integrate x402 seamlessly into NestJS applications.
Development & Contributing
Release Process
This project uses Conventional Commits and Semantic Release for automated versioning and publishing.
Commit Message Format
feat: description- New features (minor version bump)fix: description- Bug fixes (patch version bump)feat!: descriptionorBREAKING CHANGE:- Breaking changes (major version bump)docs: description- Documentation changeschore: description- Maintenance tasksci: description- CI/CD changestest: description- Test changes
Release Workflow
- Commits to the
mainbranch trigger the release workflow - Semantic-release analyzes commit messages to determine the version bump
- Generates release notes and changelog
- Publishes to npm with provenance
- Creates a GitHub release
OIDC Configuration
This project uses OpenID Connect (OIDC) for secure publishing to npm - no tokens required!
Setup Steps:
- Repository: Already configured ✅
- NPM Package: If you own this package, enable GitHub Actions publishing:
- Go to npmjs.com
- Settings → Publishing access → Enable "GitHub Actions"
- Add repository:
ParteeLabs/nestjs-x402
That's it! No secrets or variables needed.
