Skip to main content

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

If you need Drizzle for Token persistence, also install:

Step 2: Configure Environment Variables

.env.local
Never commit .env.local to version control. Make sure .gitignore includes this file.

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

The expiresAt returned by exchangeCode is the access token’s expiration timestamp, used to determine when to refresh.

Step 6: Token Persistence

The SDK provides out-of-the-box Drizzle integration:
Export the Token table in your schema:
db/schema.ts
After running migrations to create the table, implement saveToken in the callback:
For simple scenarios that don’t require a database, you can encrypt Tokens and store them in HTTP-only cookies:
lib/token-cookie.ts
The cookie approach requires updating the cookie on every Token refresh and doesn’t support server-side revocation. Option A is recommended for production environments.

Step 7: Report Billing Events

Client-side usage example:
app/dashboard/page.tsx

Step 8: Error Handling

All errors thrown by the SDK are typed exceptions that can be caught precisely:
Unified handling in the API Route:
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