Build a Chatbot Backend with 59API and Node.js
A small backend, without provider-specific plumbing
An OpenAI-compatible API lets you build a chatbot using familiar SDK methods while keeping the model provider configurable. This quick-start creates a Node.js endpoint that accepts conversation messages, calls a model through 59API, and returns an assistant reply.
59API provides low-cost, pay-as-you-go access to GPT and Claude models, including Opus, Sonnet, and Haiku. It offers native, official-quality models without downgrading and positions itself among the cheapest relays. Its compatibility with OpenAI SDKs, Claude Code, and Codex also makes it useful beyond this backend. Compare current per-model prices before choosing your default.
1. Install dependencies and configure credentials
Use Node.js 20 or later. Create a project directory, then run:
npm init -y; npm install express openai
Create a file named server.mjs. Configure these environment variables in your shell or deployment platform:
- OPENAI_API_KEY: your 59API key, stored only on the server.
- OPENAI_BASE_URL: the SDK endpoint for the relay. The service origin is https://api.59api.com; confirm the documented versioned path before using the conventional https://api.59api.com/v1.
- CHAT_MODEL: an exact model identifier available to your account. Copy it from the current model list rather than guessing a marketing name.
For example, set these variables with your shell's export command. Never embed the key in browser JavaScript, commit it to Git, or expose it through a public environment-variable prefix.
2. Create the API client and HTTP server
Paste the following sections into server.mjs in order. The SDK reads the key and base URL from the environment variables above.
import express from 'express'; import OpenAI from 'openai'; const app = express(); app.use(express.json({ limit: '64kb' })); const client = new OpenAI({ timeout: 20000, maxRetries: 1 });
Next, add a chat route. This example accepts at most 12 messages, limits each message's size, rejects privileged roles, and requires the conversation to end with a user message.
app.post('/chat', async (req, res) => { const messages = req.body?.messages; if (!Array.isArray(messages) || messages.length === 0 || messages.length > 12 || messages.some(m => !m || !['user', 'assistant'].includes(m.role) || typeof m.content !== 'string' || !m.content.trim() || m.content.length > 4000) || messages.at(-1).role !== 'user') { return res.status(400).json({ error: 'Send 1–12 user/assistant messages, ending with a user message; each must contain 1–4000 characters.' }); } try { const result = await client.chat.completions.create({ model: process.env.CHAT_MODEL, messages: [{ role: 'system', content: 'You are a concise, helpful support assistant.' }, ...messages.map(m => ({ role: m.role, content: m.content }))], max_tokens: 500 }); return res.json({ reply: result.choices[0]?.message?.content ?? '' }); } catch (error) { return res.status(error.status === 429 ? 429 : 502).json({ error: 'Model request failed. Please try again later.' }); } });
app.listen(3000, () => console.log('Chat backend listening on port 3000'));
The timeout prevents indefinitely hanging requests, while one automatic retry keeps retry amplification limited. Confirm that your chosen model supports Chat Completions and max_tokens: OpenAI compatibility does not guarantee every model supports every parameter.
3. Test a conversation
Start the service with node server.mjs. From another terminal, submit:
curl http://localhost:3000/chat -H 'Content-Type: application/json' -d '{"messages":[{"role":"user","content":"How do I reset my password?"}]}'
Expect a JSON object containing reply. For another turn, send the original user message, the returned reply as an assistant message, and the next user question. This demonstration is stateless: it does not save conversations or authenticate callers.
4. Add production controls before launch
- Protect the endpoint: require application authentication, enforce per-user rate limits, and configure CORS only for your frontend origin.
- Own conversation history: store production conversations server-side and verify ownership. Do not treat client-supplied assistant messages as trusted records.
- Budget by tokens: character limits are not token limits. Track returned usage, cap output, and summarize older turns as conversations grow.
- Route economically: evaluate cheaper models for routine questions and stronger models for difficult requests. Measure answer quality and cost together.
- Keep logs safe: record latency, status, and usage without logging keys or sensitive conversation text.
Ready to test with real traffic? Sign up for 59API, check current pricing and its referral rebate terms, and benchmark a small representative conversation set before scaling.
¿Listo para empezar?
Conecta Claude y GPT en minutos a los precios más bajos, sin recortes. Regístrate para obtener tu clave API.
Registro gratis