59API

← Back to all guides

Build a Chatbot Backend with 59API and Node.js

API · EN · 2026-10-22

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:

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

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.

Pricing · Docs

Ready to get started?

Connect Claude & GPT in minutes at the lowest prices — full-power, never downgraded. Sign up to get your API key.

Sign up free