npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

nestjs-x402

v1.3.3

Published

x402 support for NestJS

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-PAYMENT header (the signed x402 payment header). Without it the endpoint returns HTTP 402 and an accepts list describing valid payment requirements.
  • You can apply the interceptor globally via APP_INTERCEPTOR if you prefer not to decorate every route. The interceptor will ignore route without the @X402ApiOptions decorator.

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-PAYMENT header.
  • Your handler computes prices and throws X402DynamicPricing with PricingRequirement[].
  • X402Interceptor returns HTTP 402 with accepts derived from the dynamic prices.
  • Client builds a valid X-PAYMENT header (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:dev

Testing:

  • Call the protected route without X-PAYMENT to receive HTTP 402 and the accepts list.
  • Use the upstream @coinbase/x402 or other x402 client tools to construct a valid X-PAYMENT header and call the endpoint again to complete the payment flow.

Motivation

  1. The x402 payment processing system is a powerful and flexible solution for handling payments in agent-based applications.
  2. NestJS is a production-ready framework for backend development but lacks built-in support for x402.
  3. Existing x402 support is limited to Express.js, leaving a gap for NestJS developers.
  4. 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!: description or BREAKING CHANGE: - Breaking changes (major version bump)
  • docs: description - Documentation changes
  • chore: description - Maintenance tasks
  • ci: description - CI/CD changes
  • test: description - Test changes

Release Workflow

  1. Commits to the main branch trigger the release workflow
  2. Semantic-release analyzes commit messages to determine the version bump
  3. Generates release notes and changelog
  4. Publishes to npm with provenance
  5. Creates a GitHub release

OIDC Configuration

This project uses OpenID Connect (OIDC) for secure publishing to npm - no tokens required!

Setup Steps:

  1. Repository: Already configured ✅
  2. 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.