When architecting modern applications powered by artificial intelligence—whether single-page React apps, Flutter mobile clients, or browser extensions—one foundational security rule must remain non-negotiable: never query external AI APIs directly from the client side.
Exposing your secret developer credential in client-side JavaScript allows anyone to open their browser's Network Inspector and extract your token in seconds. Compromised credentials can be exploited by automated scrapers to exhaust your wallet balance or trigger service disruptions.
The industry-standard architectural solution is to deploy a backend proxy service. Your server acts as a trusted intermediary: it receives prompts from users, sanitizes incoming strings, securely injects your environment credentials, queries the TOP AI unified gateway, and returns a clean, structured payload to your frontend client.

In this hands-on engineering tutorial, we will build a production-grade Question & Answer (Q&A) REST service in Node.js using the Express.js framework, routing queries to the ultra-efficient deepseek-v4-pro (deepseek-v4-pro) reasoning model.
Step 1: Initialize Workspace and Fetch Dependencies
Create an isolated directory and initialize a Node.js project:
mkdir topai-node-backend
cd topai-node-backend
npm init -yInstall the core production dependencies:
npm install express openai dotenv corsKey operational roles for each library:
express: Minimalist, high-throughput HTTP web application framework.openai: Official client SDK providing drop-in compatibility with the gateway.dotenv: Zero-dependency module that loads variables from local.envconfigurations.cors: Configures Cross-Origin Resource Sharing headers to permit frontend connectivity.
Step 2: Configure Environment Secret Isolation (.env)
Create a .env file in your project root:
PORT=3001
TOPAI_API_KEY=tp-live-xxxxxxxxxxxxxxxxxxxxxxxxSubstitute your real tp-*** secret token issued by the TOP AI developer dashboard.
Step 3: Implement the Complete Service (server.js)
Author the primary server logic in server.js:
// language: JavaScript, file: server.js, runtime: Node.js 18+
require("dotenv").config();
const express = require("express");
const cors = require("cors");
const { OpenAI } = require("openai");
const app = express();
const PORT = process.env.PORT || 3001;
// Global Middleware Configuration
app.use(cors());
app.use(express.json());
// Instantiate Unified Gateway Client
const ai = new OpenAI({
baseURL: "https://topai.id/v1",
apiKey: process.env.TOPAI_API_KEY,
});
// Healthcheck Route for Observability
app.get("/health", (req, res) => {
res.json({ status: "healthy", timestamp: new Date().toISOString() });
});
// Primary Q&A REST Route
app.post("/api/ask", async (req, res) => {
try {
const { question, systemPrompt } = req.body;
// 1. Strict Input Sanitization
if (!question || typeof question !== "string" || question.trim().length === 0) {
return res.status(400).json({
error: "Bad Request",
message: "The 'question' property is mandatory and must contain non-empty text.",
});
}
if (question.length > 2000) {
return res.status(400).json({
error: "Payload Too Large",
message: "Inquiries are bounded to 2,000 characters for token protection.",
});
}
// 2. Assemble Structured Message Payload
const messages = [
{
role: "system",
content:
systemPrompt ||
"You are a concise, helpful, and technically precise engineering assistant.",
},
{
role: "user",
content: question.trim(),
},
];
// 3. Dispatch to deepseek-v4-pro via Unified Gateway
const completion = await ai.chat.completions.create({
model: "deepseek-v4-pro",
messages: messages,
temperature: 0.5,
max_tokens: 1000,
});
const answer = completion.choices[0]?.message?.content || "No completion generated.";
const usage = completion.usage;
// 4. Return Clean Sanitized Envelope
return res.status(200).json({
success: true,
data: {
answer: answer,
model: completion.model,
tokens: {
prompt: usage?.prompt_tokens || 0,
completion: usage?.completion_tokens || 0,
total: usage?.total_tokens || 0,
},
},
});
} catch (error) {
console.error("Upstream inference error:", error.message);
// Precise Error Status Mapping
if (error.status === 401) {
return res.status(500).json({ error: "Server authentication misconfigured." });
}
if (error.status === 402) {
return res.status(503).json({ error: "Server token balance depleted." });
}
return res.status(500).json({
error: "Internal Server Error",
message: "An unexpected error occurred during model inference.",
});
}
});
app.listen(PORT, () => {
console.log(`🚀 AI Backend Microservice listening on port ${PORT}`);
});
Step 4: Verification via Terminal Invocations
Start the local server instance:
node server.jsIn a secondary shell window, submit a test inquiry using cURL:
curl -X POST "http://topai.id:3001/api/ask" \
-H "Content-Type: application/json" \
-d '{
"question": "What is the core difference between synchronous and asynchronous code in JavaScript?"
}'The endpoint immediately responds with a structured JSON envelope:
{
"success": true,
"data": {
"answer": "Synchronous code executes sequentially, blocking subsequent operations until the current task finishes. Asynchronous execution delegates intensive operations (such as I/O or HTTP queries) to the runtime event loop, preventing main thread freezing.",
"model": "deepseek-v4-pro",
"tokens": {
"prompt": 45,
"completion": 52,
"total": 97
}
}
}Architectural Comparison: Client-Side vs Backend Proxy
| Architectural Metric | Direct Client-Side Invocations | Dedicated Backend Proxy Pattern |
|---|---|---|
| API Credential Security | Catastrophic leak risk in browser network tab | Enterprise-grade, keys isolated in server memory |
| Input Payload Sanitization | Non-existent, vulnerable to prompt stuffing | Strict, bounded character limits and validation |
| System Prompt Confidentiality | Proprietary prompts visible to all end users | Completely confidential, directives stay on server |
| Response Caching Capability | Fragmented across individual browser caches | Centralized, shared cache via Redis reduces token costs |
| Data Privacy & Compliance | Raw user strings flow uninspected to vendors | Protected, PII redaction performed before dispatch |
Introducing In-Memory Response Caching to Eliminate Token Waste
In high-volume customer-facing applications, many inquiries are fundamentally repetitive—such as operating hours, refund policies, or product specifications. Dispatching model inference for identical queries burns computational tokens unnecessarily.
Implementing a lightweight in-memory cache using node-cache or Redis delivers immediate optimization:
- Normalize incoming questions (convert to lowercase, strip trailing whitespace and punctuation).
- Check whether a cached completion exists for the generated cache key.
- If a match exists, return the cached payload in under 5 milliseconds with zero point deductions.
- If a cache miss occurs, query the gateway, store the completion with a designated Time-To-Live (TTL), and respond to the client.
Enterprise Architecture Highlights of This Pattern
This lightweight service incorporates three industry best practices:
- Zero Client Secret Exposure: The frontend client remains completely oblivious to upstream API tokens. All requests are authenticated internally on your secure server runtime.
- Input Boundary Enforcement: Imposing strict string-length checks protects your token budget against malicious oversized prompt-stuffing attempts.
- Structured Error Segregation: Internal failure codes (such as authentication or upstream balance exhaustion) are translated to clean HTTP status codes, preventing server stack traces from leaking to client applications.
Enforcing Rate Limiting at the Express Route Layer
To protect your backend microservice against abuse from automated scraping bots or runaway frontend loops, always attach an IP-based rate limiting middleware such as express-rate-limit.
Configuring a threshold of 30 requests per minute per IP address intercepts denial-of-service attempts at your server perimeter with an immediate HTTP 429 response, preventing unmetered compute requests from reaching the TOP AI gateway. This defense-in-depth posture preserves wallet capital and guarantees predictable availability for legitimate users.
With your secure backend microservice active, you can safely power web and mobile frontends with frontier intelligence.
Next, understand how balance management operates on the platform by exploring what TOP Points are and how prepaid recharge mechanics work.
Live TOP AI API Pricing for Models Mentioned
Frequently Asked Questions
Why should applications avoid calling AI APIs directly from client-side browsers?+
Direct browser calls expose your secret API keys in plaintext inside the browser developer tools network panel. A backend proxy protects credentials by keeping them strictly on the server.
Which Node.js web frameworks can host this architecture?+
While this tutorial demonstrates implementation via Express.js, the identical architecture applies seamlessly to Fastify, Hono, NestJS, or Next.js server actions.
How can repeated identical queries be optimized to reduce token bills?+
You can introduce an in-memory caching layer using Redis or local key-value stores to return identical responses instantly without invoking model inference.
Is this backend implementation ready for cloud production deployment?+
Yes. By isolating secrets in environment variables and enforcing CORS and input validation, this service deploys cleanly to Docker containers, VPS instances, or serverless functions.


