Skip to content
AI

How to Build an AI SaaS with Next.js, the OpenAI API and Crypto Subscriptions

A Coodes AI guide to building an AI SaaS: Next.js, a server-side OpenAI gateway, streaming, usage credits, crypto subscription contracts and cost control.

CoodesCoodes AI Team 5 min read · 1,187 words
How to Build an AI SaaS with Next.js, the OpenAI API and Crypto Subscriptions
Table of contents

AI SaaS products look simple from the outside: a text box, a button and a stream of generated text. Behind that box sit the parts that decide whether the business works — who is allowed to call the model, how much each call costs, how users pay, and what happens when the model provider has a bad day.

This guide from the Coodes AI team walks through the architecture we use for AI writing tools such as ChainScribe: a Next.js app, a server-side gateway to the OpenAI API, prepaid usage credits and an optional crypto subscription handled by a Solidity smart contract. The same pattern works with Claude, Gemini or an open-weight model.

The architecture at a glance

Keep the moving parts few and the responsibilities clear:

  • Next.js frontend (App Router) for the landing page, dashboard, editor and billing screens.
  • Route handlers or server actions that act as the only path to the AI provider.
  • A database (PostgreSQL works well) for users, documents, credit balances and a usage ledger.
  • A payments layer: card payments, a crypto subscription contract, or both.
  • Background jobs for long generations, webhooks and blockchain event indexing.

The browser never talks to the model provider directly. That single rule prevents leaked API keys, uncontrolled spending and users bypassing your limits.

A server-side AI gateway

Wrap every model call in one small module. It authenticates the user, checks their balance, builds the prompt from a versioned template, calls the provider, records usage and returns the result. Everything else in the app calls this module instead of the SDK.

// app/api/generate/route.ts
import OpenAI from "openai";
import { requireUser, reserveCredits, settleCredits } from "@/lib/billing";
import { buildArticlePrompt } from "@/lib/prompts";

const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

export async function POST(req: Request) {
  const user = await requireUser(req);
  const { topic, tone } = await req.json();
  const hold = await reserveCredits(user.id, 10); // throws if balance is too low

  const stream = await client.chat.completions.create({
    model: process.env.AI_MODEL!,
    messages: buildArticlePrompt({ topic, tone }),
    stream: true,
    stream_options: { include_usage: true },
  });
  return streamAndSettle(stream, hold, settleCredits);
}

Put the model name in configuration, not in code. When a cheaper or better model ships, you change one variable, run your evaluation set and redeploy. An adapter interface (generate(), stream(), embed()) lets you add a second provider as a fallback without touching the UI.

Streaming responses and UX

Long generations feel broken if the screen stays empty for twenty seconds. Stream tokens to the client and render them as they arrive. Libraries such as the Vercel AI SDK handle the streaming protocol and React state for you; a plain ReadableStream works too.

  • Show a Stop button and cancel the upstream request when the user presses it, so you stop paying for tokens nobody reads.
  • Save drafts as they stream, so a closed tab does not lose paid output.
  • Show the credit cost before the user clicks Generate. Surprise charges are the fastest way to lose trust.

Usage credits and quotas

Model providers bill per token, so your pricing should map cleanly onto tokens without exposing them. Most AI SaaS products use credits: a subscription or top-up adds credits, each action spends a predictable number, and a ledger table records every change.

ActionTypical creditsWhy
Outline or title ideas1Short output, cheap model
Full SEO article10Long output, stronger model
Rewrite a section2Medium input and output

Reserve credits before the call and settle the real amount afterwards, using the usage data the provider returns. Add per-minute rate limits and a daily ceiling per account; they protect you from runaway scripts and stolen accounts.

Crypto subscriptions with a smart contract

For a Web3 audience, a subscription paid in stablecoins can replace or complement card billing. Keep the contract minimal: it accepts payment, records until when an address is subscribed and emits an event. Credits and AI usage stay off-chain in your database.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

contract AISubscriptions {
    using SafeERC20 for IERC20;
    IERC20 public immutable token;      // e.g. USDC
    address public immutable treasury;
    uint256 public immutable monthlyPrice;
    mapping(address => uint64) public paidUntil;
    event Subscribed(address indexed user, uint64 paidUntil);

    constructor(IERC20 _token, address _treasury, uint256 _price) {
        token = _token; treasury = _treasury; monthlyPrice = _price;
    }

    function subscribe(uint8 months) external {
        require(months > 0 && months <= 12, "months");
        token.safeTransferFrom(msg.sender, treasury, monthlyPrice * months);
        uint64 start = paidUntil[msg.sender] > block.timestamp ? paidUntil[msg.sender] : uint64(block.timestamp);
        paidUntil[msg.sender] = start + uint64(months) * 30 days;
        emit Subscribed(msg.sender, paidUntil[msg.sender]);
    }
}

A backend worker listens for Subscribed events, waits for enough confirmations and then credits the linked account. Link wallets to accounts with a signed message (Sign-In with Ethereum), never by trusting an address sent from the browser. Before mainnet, run through our smart contract security checklist.

Tip: Stablecoin pricing keeps your margins predictable. Pricing subscriptions in a volatile token means your AI costs, which are billed in dollars, can suddenly exceed revenue.

Controlling cost and output quality

  • Route by task. Use a small, fast model for titles, outlines and classification; reserve the strongest model for the final long-form output.
  • Cache what repeats. Identical prompts, shared system prompts and embeddings can be cached; several providers also discount repeated prompt prefixes.
  • Keep an evaluation set. Thirty to fifty real inputs with reviewed outputs let you compare prompts and models before a change reaches users.
  • Version your prompts. Store the prompt version with every generation so you can trace a bad output to the change that caused it.
  • Watch cost per active user next to revenue per user. If the gap narrows, adjust credit prices or model routing.

Security and privacy

AI features add new attack surfaces. Treat user input as untrusted: it can contain prompt injection that tries to reveal your system prompt or abuse tools the model can call. Give the model only the permissions a feature needs, validate structured output before acting on it, and moderate content where your terms require it. Document which providers receive user data in your privacy policy, and avoid sending personal data to a model when the task does not need it.

Launch checklist

  • API keys only on the server; key rotation documented.
  • Credits reserved before and settled after every call; ledger reconciles with provider invoices.
  • Rate limits, daily ceilings and alerts on unusual spend.
  • Streaming UI with stop, retry and autosave.
  • Subscription contract tested, verified on the block explorer and owned by a multisig.
  • Evaluation set passing for the model and prompt versions you ship.
  • Pages optimized for Core Web Vitals — see our Next.js performance guide.

Conclusion

A reliable AI SaaS is mostly good plumbing: one server-side gateway to the model, clear credit accounting, a small and audited payment contract, and a habit of measuring quality and cost before every change. Get those right and swapping models or adding features becomes routine.

If you would rather start from working code, the ChainScribe theme ships this architecture out of the box, and the Coodes AI team can customize it or build your AI product from scratch.

Written by the Coodes AI Team

We build premium Web2 & Web3 themes and help teams ship dApps, SaaS platforms and Flutter apps.

Talk to us

Related articles

Architecting a Multi-Wallet Crypto App in Flutter Mobile
12 min read

Architecting a Multi-Wallet Crypto App in Flutter

Clean architecture, secure key storage, HD wallets, multi-chain abstraction and WalletConnect: how to structure a production multi-wallet crypto app in Flutter.

Read article

Ready to Build Something Amazing?

Join thousands of developers who trust our themes for their projects. Professional designs, clean code, and ongoing support.