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
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.





