## Why Indie Developers Need This Article
Why Indie Developers Need This Article
Let me start with a before-and-after comparison from my own experience. Last month, I added AI capabilities to a side project. The first time, I called the model API directly from the frontend: API key exposure risk, CORS errors, and switching providers required changes in three places—it took nearly an entire afternoon from writing code to getting it running. The second time, I built a proxy gateway layer using Next.js Route Handlers. From registration to running the first piece of code took less than 30 minutes. After that, every time I switched model providers, I only changed one line—the base_url—done in two minutes.
The time saved isn't a one-time gain. Every integration session, every model switch, every request troubleshooting—this proxy layer keeps saving time. For indie developers and small teams, this kind of "set up once, reuse forever" infrastructure offers extremely high cost-effectiveness.
Overall Approach
The architecture is simple:
Frontend → Next.js Route Handler (/api/chat) → ThisToken.AI Gateway → Various ModelsThe frontend only communicates with your own /api/chat; the API Key lives in server-side environment variables and never leaves the server. Meanwhile, gateway services like ThisToken.AI handle the "multiple providers, unified interface" layer for you—OpenAI-compatible format, so when switching providers, the interface stays the same and you only change the model name.
Step 1: Register and Get an API Key
- Open https://api.thistoken.ai/register and sign up with your email (indie developers can register a personal account; small teams should share an organization account for easier unified usage tracking later).
- After logging in, go to the console, create a new Key on the API Key management page, and copy and store it securely. The Key is only shown in full once, at creation time.
- Billing is based on the pricing page on the official website. New accounts can usually start with a small amount to try things out, then decide how much to top up once the flow works.
Step 2: Write Your First Proxy Route
Create app/api/chat/route.ts in the project root directory (App Router syntax):
// app/api/chat/route.ts
import { NextRequest, NextResponse } from "next/server";
// 复用底层 fetch,生产环境建议自己加连接池/超时控制
const GATEWAY_BASE_URL = "https://api.thistoken.ai/v1"; // 这就是那行关键配置
export async function POST(req: NextRequest) {
const apiKey = process.env.THISTOKEN_API_KEY;
if (!apiKey) {
return NextResponse.json({ error: "Missing THISTOKEN_API_KEY" }, { status: 500 });
}
const body = await req.json();
const upstream = await fetch(`${GATEWAY_BASE_URL}/chat/completions`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${apiKey}`,
},
body: JSON.stringify({
model: body.model ?? "gpt-4o-mini", // 换模型只改这里
messages: body.messages,
}),
});
if (!upstream.ok) {
const errText = await upstream.text();
return NextResponse.json(
{ error: "Upstream error", detail: errText },
{ status: upstream.status }
);
}
const data = await upstream.json();
return NextResponse.json(data);
}Put the environment variable in .env.local:
THISTOKEN_API_KEY=sk-你的keyIf your project already uses the official SDK, switching to the gateway also only requires one line of change:
import OpenAI from "openai";
const client = new OpenAI({
apiKey: process.env.THISTOKEN_API_KEY,
baseURL: "https://api.thistoken.ai/v1", // 只改这一行
});Step 3: Run and Verify
Start npm run dev and test with curl:
curl -X POST http://localhost:3000/api/chat \
-H "Content-Type: application/json" \
-d '{"messages":[{"role":"user","content":"你好,介绍一下你自己"}]}'If you get a normal JSON completion response back, the whole chain works.
Before and After: How Much Does This Proxy Layer Actually Save
I did a rough time accounting based on my own project:
- Key security: Before, I either had to bundle the Key into the frontend package (unacceptable) or hand-write a temporary Node script to forward requests (40+ minutes each time). Now, the Route Handler is a framework-native capability—10 minutes to write, and the Key only lives on the server.
- Switching providers: Before, connecting directly to various SDKs with different interface formats and authentication methods took at least half a day to switch completely. Now, going through the gateway with unified OpenAI-compatible format, the actual work is changing
baseURLand the model name—two minutes. - Troubleshooting: All requests go through your own
/api/chat. Add one line of logging and you can see the complete request and response. Before, when the frontend connected directly, I spent an hour debugging a 401 by switching back and forth between browser DevTools and provider documentation.
Note that the time figures mentioned here are records from my personal project; your situation will differ. The costs of the gateway and various models are subject to the pricing pages on the official websites, which is outside the scope of this article.
Two Common Pitfalls
- Don't use
await res.json()for streaming responses. If you need to supportstream: true, justreturn new Response(upstream.body, { headers: { "Content-Type": "text/event-stream" } })to pass the stream through—don't parse it along the way. - Don't forward the
req.json()body as-is all the way through. Validate first, then whitelist fields—this blocks most malformed requests. The proxy layer is your only server-side checkpoint, and it's worth writing ten extra lines of validation code.
Final Thoughts
The combination of this proxy layer plus the gateway turns "adding AI capabilities" from something you have to fiddle with every single time into an asset you configure once and benefit from long-term. If you don't have an account yet, head over to https://api.thistoken.ai/register to sign up, get your Key, and paste the code above into your project to get it running—once the first piece of code works, everything else is just a matter of changing configuration.
---
Ready to try it yourself? Sign up at https://api.thistoken.ai/register to get your API key and start building.
Vous voulez essayer Token.AI ?
Créez une API Key au niveau du projet, activez les canaux dans la console et configurez le routage, les budgets et les journaux d'audit.
注册 ThisToken.AI 并获取 API Key