x402 in Next.js: call paid APIs from server code

In Next.js you call x402 endpoints from server code — a route handler or server action — so your wallet key never reaches the browser. The @2sio/sdk client does the rest.

Call from a route handler

Keep the wallet key in a server-only env var and call the endpoint inside an app-router route handler:

app/api/forecast/route.tstypescript
import { TwoS } from '@2sio/sdk'

const client = new TwoS({ privateKey: process.env.EVM_PRIVATE_KEY as `0x${string}` })

export async function GET() {
  const res = await client.weather.zip({ zip: '94103' })
  return Response.json(res.data)   // real NWS forecast, paid per call
}

Keep payments server-side

Never put a funded wallet key in client components or NEXT_PUBLIC_ vars — it would be exposed in the browser bundle. Call x402 endpoints from route handlers, server actions, or server components only, and return just the data to the client.

Try before you wire payment

Use trial mode while building so you do not spend anything during development:

trial modetypescript
const client = new TwoS({ trial: true })  // free real calls, no key

Call a live x402 API right now — no signup.

Browse the full endpoint directory, grab the quickstart, or read the llms.txt manifest. Every endpoint is keyless and pay-per-call.

FAQ

How do I use x402 in a Next.js app?
Call @2sio/sdk from server code — a route handler, server action, or server component — with your wallet key in a server-only env var. Return the data to the client; never expose the key in the browser.
Can I call x402 from a client component?
Not with a funded server wallet — that key would leak into the browser bundle. Proxy the call through a route handler. (A browser app could pay from a user-connected wallet, but that is a different, user-funded pattern.)

Related

Topics: x402 next.js · x402 nextjs · x402 next js example · x402 react · x402 server action