Next.js Integration
Add x402 payments to your Next.js API routes and server actions
Installation
npm install @getconduit/x402-nextjsAPI Route Handler
// app/api/premium/route.ts
import { withX402 } from '@getconduit/x402-nextjs'
export const GET = withX402(
async (request) => {
// This handler requires payment
return Response.json({
message: 'Premium content unlocked!',
data: { /* your premium data */ }
})
},
{
facilitatorUrl: 'https://getconduit.io/api/facilitator',
network: 'solana',
price: 0.01
}
)Server Actions
// app/actions.ts
'use server'
import { withX402Action } from '@getconduit/x402-nextjs'
export const getPremiumData = withX402Action(
async (userId: string) => {
// Fetch premium data
const data = await db.query('SELECT * FROM premium WHERE user_id = $1', [userId])
return data
},
{
facilitatorUrl: 'https://getconduit.io/api/facilitator',
network: 'solana',
price: 0.02
}
)Client Component
// app/components/premium-content.tsx
'use client'
import { useX402 } from '@getconduit/x402-nextjs/client'
export function PremiumContent() {
const { data, loading, error, pay } = useX402('/api/premium')
if (loading) return <div>Loading...</div>
if (error) return <div>Error: {error.message}</div>
if (!data) {
return (
<button onClick={pay}>
Unlock Premium Content (0.01 USDC)
</button>
)
}
return <div>{data.message}</div>
}Middleware
Protect multiple routes with middleware:
// middleware.ts
import { x402Middleware } from '@getconduit/x402-nextjs'
export default x402Middleware({
facilitatorUrl: 'https://getconduit.io/api/facilitator',
network: 'solana',
price: 0.01
})
export const config = {
matcher: '/api/premium/:path*'
}