Integrate with Next.js
Add billing and payments to your Next.js application.
Use this pre-built prompt to integrate Commet faster with AI assistants.
Install
pnpm add @commet/node @commet/nextnpm install @commet/node @commet/nextyarn add @commet/node @commet/nextbun add @commet/node @commet/nextConfigure
COMMET_API_KEY=ck_sandbox_xxximport { Commet } from '@commet/node'
export const commet = new Commet({
apiKey: process.env.COMMET_API_KEY!,
environment: 'sandbox',
})Create Customer and Subscribe
customers.create is idempotent — if a customer with the same id already exists, it returns the existing record.
'use server'
import { redirect } from 'next/navigation'
import { commet } from '@/lib/commet'
export async function subscribe(customerId: string) {
await commet.customers.create({
email: 'user@example.com',
id: customerId,
})
const subscription = await commet.subscriptions.create({
customerId,
planCode: 'pro',
})
redirect(subscription.data.checkoutUrl!)
}The customer is redirected to checkout to complete payment.
Check Access
export async function getSubscription(customerId: string) {
const { data } = await commet.subscriptions.get(customerId)
return data
}export async function canUseFeature(customerId: string, feature: string) {
const { data } = await commet.features.check({ code: feature, customerId })
return data.allowed
}Track Usage
export async function trackApiCall(customerId: string) {
await commet.usage.track({
customerId,
feature: 'api_calls',
value: 1,
})
}Usage is aggregated and billed at end of period.
Customer Portal
import { CustomerPortal } from '@commet/next'
export const GET = CustomerPortal({
apiKey: process.env.COMMET_API_KEY!,
getCustomerId: async (req) => {
return 'user_123'
},
})<a href="/api/commet/portal">Manage Billing</a>Related
How is this guide?