What You’ll Build
This tutorial walks you through building a Next.js 14+ (App Router) full-stack application from scratch, implementing Profy OAuth login, secure Token storage, and per-use billing event reporting. After users click “Login with Profy” and complete authorization, the application automatically manages the Token lifecycle and reports billing events to Profy when users trigger paid actions.Prerequisites
Profy Developer Account
Registered a Profy account and created an App in the developer dashboard to obtain your Client ID and Client Secret
Development Environment
Node.js 18+, npm/pnpm/bun, basic Next.js and React experience
Step 1: Create a Next.js Project and Install Dependencies
Step 2: Configure Environment Variables
.env.local
Step 3: Initialize the SDK
The
ProfyApp instance should be used as a singleton on the server side. Never expose clientSecret to the client.Step 4: Create the OAuth Login Page
app/page.tsx
Step 5: Handle the OAuth Callback
Step 6: Token Persistence
Option A: Using DrizzleTokenStore (Recommended)
The SDK provides out-of-the-box Drizzle integration:db/schema.ts
saveToken in the callback:
Option B: Encrypted Cookie (Lightweight Scenarios)
For simple scenarios that don’t require a database, you can encrypt Tokens and store them in HTTP-only cookies:lib/token-cookie.ts
Step 7: Report Billing Events
app/dashboard/page.tsx
Step 8: Error Handling
All errors thrown by the SDK are typed exceptions that can be caught precisely:app/api/report-event/route.ts
Complete Project Structure
FAQ
Next Steps
Per-Use Billing SaaS
PER_USE mode: fixed-price per-use billing
AI Metered Billing
METERED mode: billing by token consumption for AI model calls
Webhook Event Handling
Receive real-time user event notifications from the Profy platform
Token Management Best Practices
Multi-user management, concurrent refresh, secure storage

