Getting started with Next.js
Start accepting x402 payments in your Next.js app in 2 minutes.You can find the full code for this example here.
Step 1: Create a new app
Use your favorite package manager:npm (npx)
pnpm
bun
Step 2: Set your environment variables
Copy the example env and fill in your values (e.g.cp .env-local .env or cp env.example .env.local).
Step 3: Explore the app structure
The example uses a proxy for page routes and withX402 for API routes:- paymentProxy (in
proxy.ts) protects page routes and returns a paywall when payment is required. - withX402 wraps individual API route handlers so payment is settled only after a successful response.
Step 4: Preview the example routes
Protected Page Route
The/protected page is protected using paymentProxy.
The proxy in proxy.ts configures the resource server, paywall, and protected routes:
Weather API Route (using withX402)
The/api/weather route demonstrates the withX402 wrapper for individual API routes:
paymentProxy vs withX402
ThepaymentProxy function is used to protect page routes. It can also protect API routes, however this will charge clients for failed API responses.
The withX402 function wraps API route handlers. This is the recommended approach to protect API routes as it guarantees payment settlement only AFTER successful API responses (status < 400).
Step 5: Run the server
Your Next.js app is now accepting x402 payments!
Step 6: Test the server
The starter includes a built-in paywall at the home page. Navigate to http://localhost:3000 to test payments directly. You can also test programmatically by following the fetch example or axios example.Going to production
The starter works on the free tier out of the box β no API keys required. When youβre ready for production, create a merchant account at merchant.payai.network, get your API keys, and add them to your.env:
@payai/facilitator package automatically detects these environment variables and authenticates your requests to the facilitator. See Facilitator Pricing for tier details and Facilitator Authentication for the full protocol reference.
x402 reference
For a deeper dive into message shapes, headers, verification and settlement responses, see the x402 Reference.Need help?
Join our Community
Have questions or want to connect with other developers? Join our Discord server.

