This guide walks through a full sample app. For the short, step by step version of the same
integration, see the Gen AI Technical Integration
Guide. Gen AI
Requirements explains why it is
required.
generation credit wallet in the Customer Credits API when they sign up and verify their email, Creem adds purchased credits to it, and every prompt is validated through the Moderation API. Each debit carries the ID of the moderation result that cleared its prompt.
Demo
Aperture implements the following four-step order for every generation: Try it at aperture-creem.vercel.app. The tabs below show the possible prompt moderation results in the application:- allow
- deny
- flag
- error
An ordinary prompt, screened by the live Moderation API and verified to pass. It clears moderation, debits 5 credits, renders a poster into the gallery, and the wallet drops by 5.

Prerequisites
Clone the project
Since there’s a lot to cover in this application, the better way is to clone the project, install its dependencies, and then learn the core parts around moderation and billing with Creem. Run the following commands to clone and install the project:creemis the official SDK (version 1.14.0 or later) through which the Customer Credits and Moderation are managed.@creem_io/better-authis the Better Auth plugin of Creem.better-authhandles email and password sign-in.@neondatabase/serverlessto query Postgres in serverless functions over HTTP requests.
Provision a Serverless Postgres
To set up a serverless Postgres, go to the Neon console and create a new project. Once your project is created, you will receive a connection string that you can use to connect to your Neon database. The connection string will look like this:shouldWrap
DATABASE_URL in the .env.local file.
Configure Creem credentials
1
Copy your API key
Grab your API key from the Developers section of the dashboard and set it as
CREEM_API_KEY. The app picks test vs production mode from the key prefix (creem_test_ is test mode).2
Create the three credit packs
Each pack (Starter, Pro, and Studio) maps to a one-time Creem product with an AI generation credits feature. The feature holds the number of credits the pack grants: when a user pays, Creem adds them to that user’s generation wallet. With It prints the three
CREEM_API_KEY set, run the setup script to create all three at once:CREEM_PRODUCT_* lines to paste into .env.local. Re-running in the same mode returns the existing products instead of creating duplicates.Prefer the dashboard? In the products tab, create one product per pack. In Delivery, click Add, choose New AI generation credits, and set the credit amount (200, 1000 and 3000). Then copy each product ID (it starts with prod_) into CREEM_PRODUCT_STARTER, CREEM_PRODUCT_PRO, and CREEM_PRODUCT_STUDIO.3
Generate a Better Auth secret
Better Auth signs sessions with
BETTER_AUTH_SECRET. Generate a random value with the following and update in the .env.local file:CTRL-C to stop the server and now let’s move to understanding the codebase.
Initialize the Creem SDK client
Every call in the app reuses a single SDK instance fromsrc/lib/creem/client.ts:
server option (api.creem.io for production, test-api.creem.io for test) and adds the x-api-key header to every request. The app sets server by checking whether the API key starts with creem_test_.
Set up the database schema
Creem is the source of truth for balances, so the schema indb/schema.sql only has the Better Auth tables and a few application tables. Two of them related to billing are as follows:
credit_accountis a lookup table. It does not store a balance. It only remembers which Creem customer (cust_…) and generation wallet (cca_…) belong to which user, so a request can ask Creem for the live balance of the customer.credit_ledger_cacheis a read model. It mirrors every credit and debit. It enables fetching the transaction history page without a round trip to Creem on every page load. It also keeps an audit trail after an account is closed.
Screen the prompt before generation
Creem requires moderation on AI generation products, so the wrapper insrc/lib/creem/moderation.ts follows three rules:
- Screen the prompt before anything else.
- Block on both
denyandflag. - If the call errors or times out, block. Never generate on an unknown answer.
- Keep the
idof the result. The debit needs it.
allowed is true only on an explicit allow. Every other branch, including the empty catch, returns false. So the request is blocked on any error, timeout, or an unknown response code. This ensures that generations are always moderated. On allow, the result also carries the moderation id, which the route passes to the debit.
Implement the wallet layer
Every balance change goes through one module,src/lib/wallet.ts and is used by the routes and the email verification hook. It calls the Creem API on every generation, and then it mirrors the actions into Postgres for history and auditing.
The wallet layer is comprised of two files:
src/lib/wallet.ts: exposes wallet controls, such asensureWalletForUser,debitForGeneration,refundDebit,getBalance,listHistory, and the account controls (freeze,unfreeze,close).src/lib/creem/credits-creem.ts: adapter overcreemClient.customerCredits.*. It makes the Creem calls and maps the camelCase responses onto the application’s snake_case types.
Create the wallet at sign-up
Every user gets a Creem customer and a credit wallet as soon as they sign up and verify their email. The wallet has to be namedgeneration: that name makes it the AI generation wallet, so purchased credits land in it and every debit from it requires a moderation result.
findOrCreateCustomerinsrc/lib/creem/customers.tslooks the customer up by email and creates it withexternalIdset to the app’s user id if it does not exist. A customer it finds with a differentexternalIdbelongs to another user of your app and is refused. One without anexternalIdis claimed for this user.initialBalancegives new users 20 free credits. Free credits work like paid ones: spending them still requires a moderation result.- Creating a wallet has no idempotency key, so the function serializes per-user creation behind a transaction-scoped advisory lock (
pg_advisory_xact_lock) and re-checks the table inside the lock. Exactly one wallet is created per user.
afterEmailVerification hook in src/lib/auth.ts. Sign-in requires a verified email, so every signed-in user can have a wallet:
Debit with the moderation ID
A generation is paid for with a debit from the generation wallet. It carries two things besides the amount: an idempotency key and the moderation ID.- The idempotency key. Retries happen for ordinary reasons: a user double-clicks, or a network blip makes a client resend a request that already succeeded. An idempotency key means Creem treats the retry as the same operation and does not change the balance a second time.
- The moderation ID. Creem refuses a debit from the generation wallet unless it carries the ID of an
allowresult from your store that is at most 24 hours old and has not paid for another debit.
cacheMovement mirrors the same entry into credit_ledger_cache so the history page can show its reference.
The adapter turns Creem’s error codes into typed errors for the route:
insufficient_balance lets the application show the user a clean “you need N credits” (instead of a raw API error). A moderation_* code, such as moderation_id_required or moderation_result_already_used, means Creem refused the debit because of its moderation result. In both cases nothing was debited.
Read current and point-in-time balances
The balance read passes an optionalat timestamp to Creem:
- With no
at, you get the current balance. - With an ISO timestamp, you get the balance at that moment. This is helpful for a support question like “how many credits did this customer have on the 3rd August”.
Reverse a debit
Creem has a reversal operation enabling you to skip manual re-credits. When a generation fails after you’ve charged, you can reverse the exact debit transaction:Implement the generation route
When a generation is requested viasrc/app/api/generate/route.ts, it goes through the four steps shared earlier in-order. In this section, we cover each step in detail. Let’s start with how requests are validated.
Validate the request
The route uses a withUser re-usable function to allow only authenticated user to request generations. It parses the body with Zod, sets the cost from the media type (an image is 5 credits, a video is 40), and accepts an optional client-supplied idempotency key so a retry from the browser doesn’t double-charge or double-generate. It also validates the optional reference image. TheimageDataUrl has to be a base64 image data URL, and the route rejects anything over 2.5 MB (as a demonstration of enforcing limits).
Replay a completed request
The route then checks whether this idempotency key already produced a finished generation. If it did, it returns that result and runs nothing else. That includes a generation that failed and was refunded: one key is one generation, and Creem refuses a second debit under the same key, so a client that wants to try again sends a new key.ensureWalletForUser and checks that it is active. A frozen or closed account is turned away with a clear status. Then the following four steps run:
Step 1: moderate
If the prompt doesn’t clear, the route records arejected generation and returns. Nothing has been charged from the user in this case.
Step 2: debit
The user is then charged (before the model runs). A separate idempotency key derived from the request key keeps the debit itself safe to retry, andmoderationId links the debit to the result from step 1. One moderation ID pays for one debit. An insufficient balance is caught as a 402, and a debit Creem refuses because of its moderation result is returned as a blocked prompt. In both cases nothing was charged, and the generation is recorded so the attempt is not lost.
Step 3 and 4: generate, then return or reverse
Then, the model runs to generate the desired asset. If it fails, the route catches that failure and reverses the exact debit, so the user keeps their credits.refundedis only reported after the reversal succeeds.- If the reversal fails and the customer is still charged, the route marks the row
failed, logs a warning with the generation id, and tells the customer the team will sort it out. - The
generationtable records each step: the moderation decision, the debit transaction id, and the final status to ensure that you can audit the events in future.
Prevent duplicate charges with an advisory lock
Idempotency keys make a retry safe once the first request has finished. Two requests with the same key can also be in flight at the same moment, though, like a client that retries before the first response comes back. If both slipped past the replay check together, both would debit and both would call the model. The generation route closes that window with a Postgres advisory lock. The flow runs on a dedicated connection while holding a lock keyed on the user id and the idempotency key. A racing duplicate blocks on the lock until the first request finishes, then reaches the replay check and returns the first result instead of charging again.- Since two independent generations will use different keys, the lock in the application code only ever serializes true duplicates.
- If the unlock query fails, it destroys the connection to Postgres so a session lock can not be reused by another request from the pool.
Sell credit packs
The pricing page lists three packs, defined insrc/lib/packs.ts, and each one maps to a Creem product through the env vars you set earlier. The credits number here is display copy for the pricing card. The amount a purchase grants is the one set on the product’s AI generation credits feature, so keep the two in sync:
src/app/api/checkout/route.ts, which opens a Creem checkout for that product and returns the URL. The important line is customer.id: the checkout runs as the Creem customer created for the user, so the credits land in that user’s generation wallet.
Creem credits the wallet
When the payment succeeds, Creem adds the product’s credits to the buyer’s generation wallet as part of the payment. The app has no credit call and no webhook handler for purchases, so there is no double crediting, retry or failed webhook to handle. The balance widget reads the new balance from Creem on the next refresh.Protect routes with authentication checks
The application dashboard and API routes are protected by two checks:-
src/proxy.tsthat denies any request to a protected route with no session cookie:Note that the cookie check doesn’t prove the session is valid. It only rejects requests that carry no session cookie at all. -
Every route re-checks the session server-side with
withUserinsrc/lib/session.ts, which calls Better Auth’sgetSession.
Freeze, unfreeze, and close accounts
Running a credits product means you eventually have to freeze a suspicious account, unfreeze it after review, or close one. Those functionalities are available in the wallet layer of the application, and are exposed throughsrc/app/api/credits/account/route.ts:
credit_ledger_cache table in the database.
The transaction history itself comes from src/app/api/credits/history/route.ts where the wallet reads the live entries from Creem and populates each one with the reference and kind from the cache (database) mirror, because Creem’s /entries endpoint leaves the reference off.
Swap in a real model
In Aperture’s code, the AI-powered generator is a black box in an interface insrc/lib/generator/index.ts. The default is a StubGenerator that renders a gradient poster from the prompt, to demonstrate the billing and moderation flow runs with no model credentials and at no cost. To use a real model, implement the interface and register it like following:
case 'fal' in getGenerator() and set GENERATOR=fal as the environment variable. This allows you to use any model (or even multiple ones) without any change in the billing or moderation flow.
Deploy to Vercel
- Push the project to a Git repo and import it into Vercel.
- Set every environment variable from your
.env.local. - Set
BETTER_AUTH_URLandNEXT_PUBLIC_APP_URLto your Vercel URL. - Run
pnpm db:migrateonce against your production database.
Summary
You now have a safe, metered AI image and video generator built with Next.js and Creem. Creem holds the credits, adds purchased ones to each user’s generation wallet and screens the prompts, and Postgres keeps a mirror for history and auditing. Every generation runs in the same order: moderate, debit with the moderation ID, generate, then return or reverse. When you’re ready for a real model, simply swap theStubGenerator behind its interface.

