Next.js middleware that automatically retires verified ecological credits after every AI response. Set it and forget it.
npm install @toknwrks/regen-compute-nextjs @toknwrks/regen-compute-clientGet an API key at compute.regen.network, then add it to your environment:
Local development — add to .env.local:
REGEN_API_KEY=rfa_...
Production — add REGEN_API_KEY as an environment variable in your hosting platform:
- Vercel: Project Settings → Environment Variables
- Netlify: Site Settings → Environment Variables
- Railway / Render / Fly.io: your project's environment/secrets settings
The API key is only ever used server-side inside your route handler. It is never exposed to the browser.
Wrap your existing AI route handler with withRegen. Your handler is unchanged — retirement happens in the background after the stream finishes.
// app/api/chat/route.ts
import { withRegen } from '@toknwrks/regen-compute-nextjs'
async function handler(req: Request) {
// your existing AI route, completely unchanged
const stream = await callYourAI(req)
return new Response(stream, { headers: { 'Content-Type': 'text/event-stream' } })
}
export const POST = withRegen(handler, {
apiKey: process.env.REGEN_API_KEY!,
})That's it. Every time someone hits your AI route, the session footprint is estimated and credits are retired on Regen Network — automatically, in the background, without blocking the response.
withRegen(handler, {
// Required
apiKey: process.env.REGEN_API_KEY!,
// Optional
creditClass: 'C', // C, BT, MBS, KSH, USS (default: 'C')
beneficiaryName: 'Acme AI', // appears on the certificate
jurisdiction: 'US', // ISO code
reason: 'AI session footprint', // default
// Hooks (fire-and-forget, errors are swallowed)
onRetire: ({ session_minutes, co2_kg, tx_hash, certificate_url }) => {
console.log(`Retired for ${session_minutes.toFixed(2)}min session (${co2_kg}kg CO₂)`)
console.log(`Certificate: ${certificate_url}`)
},
onError: (err) => {
console.error('Regen retirement failed:', err)
},
// Disable in tests
enabled: process.env.NODE_ENV !== 'test',
})- Request comes in — start timer
- Your handler runs, response streams back to the user
- When the stream finishes, duration is measured
GET /api/v1/footprint?session_minutes=Xestimates ecological footprintPOST /api/v1/retireretires the equivalent credits on Regen NetworkonRetirefires with the result (tx hash + certificate URL if on-chain)
Retirement is always fire-and-forget. If it fails for any reason, your users are never affected.
Your API key is all that's required. The Regen Compute server handles wallet signing and on-chain retirement. If no wallet is configured on their end, you get a marketplace link instead — fully graceful.
Apache-2.0