Add the official x402 package to your Next.js app and point it at x402Go. Requests to your paid routes get a payment request, and your handler runs once the customer has paid. If your handler fails, the customer isn’t charged.
This guide shows the Next.js-specific setup. For credentials, choosing a token, and going live, see the Quickstart.
Install
In an existing Next.js App Router project:
Install matching versions of the @x402/* packages. If you see type errors, check the SDK’s installation guide for the versions it expects.
Environment variables
Add these to .env.local. Next.js loads the file automatically. Get your API key and payment address from the x402Go dashboard, and the token values from GET /supported.
Never add the NEXT_PUBLIC_ prefix to these variables. Next.js sends prefixed variables to the browser, which would expose your API key.
Set up x402 once
Create lib/x402.ts. Your routes share this setup.
Protect an API route
Wrap the route’s handler with withX402:
The key ('/api/premium') must match the route’s URL path exactly as it is served, including any basePath you’ve configured. If it doesn’t match, the route runs without payment protection. Always test an unpaid request, as shown below.
Routes you don’t wrap stay free.
Protect pages or many routes at once
To protect pages, or several routes with one configuration, use paymentProxy instead. Create proxy.ts in your project root (middleware.ts, exporting middleware, on Next.js 15 and earlier):
The matcher must cover every route in the config. A protected route missing from the matcher isn’t checked.
Accept more than one token
Add more entries to accepts, one per token. Each token needs its own asset, name, and version from /supported. See Express for an example. The same configuration works in Next.js.
Test it
An unpaid request must return 402 Payment Required with the payment request in the response. If you get your content instead, the route isn’t protected. Check that the path in your config matches the URL. To complete a payment, use an x402 client. The Celo Sepolia sandbox has a working example with test tokens.
Before you deploy
- Keep
FACILITATOR_API_KEY in server-side environment variables only, never NEXT_PUBLIC_.
- Use your payment address as
PAY_TO, not your payout wallet. Payments to any other address are rejected.
- Set all variables in your hosting provider, including for the build step. Next.js loads your route files during
next build, so a missing variable fails the build. This is intentional, so a misconfigured