Building an AI Service API

Receive browser messages with Express, call a model, and forward its streaming answer to the frontend.

🎯 Introduction

You can now receive streaming model answers in a Node.js terminal. To display them on a Vue chat page, the browser needs a way to receive that content too.

API keys must stay out of browser code, where others could obtain them and consume your model credit. Add an Express endpoint between the browser and model: the browser sends questions and displays answers, while the backend calls the model and returns results.

This article implements POST /api/chat, covering message input, forwarding streamed answers, disconnected clients, and failed calls.


🧱 How the Browser Receives an Answer

A request follows the flow below. The browser sends the question and displays the answer; Express calls the model and forwards its results:

  1. 1
    The browser sends a question to Express
  2. 2
    Express calls the model API
  3. 3
    The model API streams text chunks to Express
  4. 4
    Express streams NDJSON to the browser

The browser accesses only its own /api/chat endpoint. It does not need the AIHubMix URL or API key. The key stays in the backend's .env file.

Why Define a Response Format?

The chat page should display text as it arrives instead of waiting for the full answer. Express will return NDJSON, with each JSON object on its own line, separated by \n.

For example, the browser might receive:

{"type":"delta","text":"Hello"}
{"type":"delta","text":", I am an AI assistant."}
{"type":"done","finishReason":"stop"}

We use these message types:

  • delta: A new text chunk from the model. The browser appends text to the current answer.
  • done: The stream has ended; finishReason records the model's finish reason.
  • error: If an exception occurs after text transmission has begun, this message tells the browser that generation was interrupted.
Both SSE and NDJSON support streaming. We use NDJSON so the browser can identify delta, done, and error as one JSON object per line. The OpenAI SDK already handles upstream SSE, so we do not parse it ourselves.

🛠 Create an Express Endpoint

Continue with ai-sdk-course, using Node.js 24.x and the installed openai@7.62.0. Add Express 5.1.0:

npm install --save-exact express@5.1.0

Your existing .env needs no changes:

AI_API_KEY=your-aihubmix-api-key
AI_BASE_URL=https://aihubmix.com/v1
AI_MODEL=gpt-4o-mini

Step 1: Understand Incremental Responses in Express

In Express, app.post("/api/chat", ...) handles POST requests to this path. The handler's req represents the request and res the response.

First, examine a route that does not call the model yet:

app.post("/api/chat", (req, res) => {
    res.setHeader("Content-Type", "application/x-ndjson; charset=utf-8");

    res.write(JSON.stringify({ type: "delta", text: "Hello" }) + "\n");
    res.write(JSON.stringify({ type: "delta", text: "!" }) + "\n");
    res.write(JSON.stringify({ type: "done" }) + "\n");
    res.end();
});

Only the route is shown here. The complete example later creates app and starts the server. This fixed text illustrates response handling:

  • res.write() writes data to the browser while allowing more data to follow.
  • res.end() ends the HTTP response; no further data is sent.

Because these res.write() calls run consecutively, the client may receive all three lines almost simultaneously. First learn how to write incrementally; after connecting the model, text will be forwarded as it is generated.

Step 2: Read and Validate the User Message

The browser sends a JSON body like this to /api/chat:

{"message":"Introduce Node.js"}

Express parses the body with express.json() and exposes it through req.body. The endpoint accepts only nonempty strings and limits their length:

app.use(express.json({ limit: "16kb" }));

app.post("/api/chat", async (req, res) => {
    const message = req.body?.message;

    if (typeof message !== "string" || !message.trim() || message.length > 2000) {
        return res.status(400).json({ error: "Enter a message of 1–2000 characters" });
    }

    // Call the model only after validation succeeds
});

16kb limits the entire request body's byte size, while 2000 limits message length. Failed validation returns HTTP 400 without calling the model.

Step 3: Forward Model Chunks to the Browser

Streaming Output introduced choice.delta.content for reading newly generated text. Replace terminal output with res.write() to return that text to the browser.

The following snippet shows only model invocation and text forwarding. client is the SDK client created earlier, and message is the validated input from the request body. The complete variables and route appear later.

const stream = await client.chat.completions.create({
    model: process.env.AI_MODEL,
    messages: [{ role: "user", content: message }],
    stream: true
});

res.setHeader("Content-Type", "application/x-ndjson; charset=utf-8");

let finishReason = null;

for await (const chunk of stream) {
    const choice = chunk.choices[0];
    if (!choice) continue;

    const text = choice.delta?.content;
    if (text) {
        res.write(JSON.stringify({ type: "delta", text }) + "\n");
    }

    if (choice.finish_reason != null) {
        finishReason = choice.finish_reason;
    }
}

res.write(JSON.stringify({ type: "done", finishReason }) + "\n");
res.end();

There are two main steps:

  1. As each text chunk arrives, immediately write a delta line.
  2. After the model stream ends, write done and call res.end().

Some chunks contain no text, so check for text first. finish_reason explains why generation stopped: stop means normal completion, while length indicates possible truncation at a length limit.

Step 4: Handle Disconnections and Failed Calls

Suppose the user closes the page midway through an answer. Once the browser disconnects, the backend no longer needs to continue the model request.

Create an AbortController and pass controller.signal to the SDK. If the response connection closes early, call controller.abort() to attempt to cancel the upstream request.

Error handling also depends on when failure occurs:

SituationHandling
Failure before any data is sentReturn HTTP 502 with a JSON error
Failure after some text is sentWrite an NDJSON error line, then end the response
Browser already disconnectedCancel the model request and stop writing to the browser

Once HTTP headers have been sent, the status code cannot change. res.headersSent checks whether the response has already started.

Cancellation and errors involve a few edge cases. For now, understand the problem each solves; the complete code below combines the handling.


🧩 Complete Code

Create 08.server.mjs in the project root and combine the steps above:

import express from "express";
import OpenAI from "openai";

const app = express();
const client = new OpenAI({
    apiKey: process.env.AI_API_KEY,
    baseURL: process.env.AI_BASE_URL
});

app.use(express.json({ limit: "16kb" }));

app.post("/api/chat", async (req, res) => {
    const message = req.body?.message;

    if (typeof message !== "string" || !message.trim() || message.length > 2000) {
        return res.status(400).json({ error: "Enter a message of 1–2000 characters" });
    }

    const controller = new AbortController();
    let finished = false;

    res.on("close", () => {
        if (!finished) controller.abort();
    });

    try {
        const stream = await client.chat.completions.create({
            model: process.env.AI_MODEL,
            messages: [{ role: "user", content: message }],
            stream: true
        }, { signal: controller.signal });

        res.setHeader("Content-Type", "application/x-ndjson; charset=utf-8");
        res.setHeader("Cache-Control", "no-cache, no-transform");
        res.setHeader("X-Accel-Buffering", "no");

        let finishReason = null;

        for await (const chunk of stream) {
            const choice = chunk.choices[0];
            if (!choice) continue;

            const text = choice.delta?.content;
            if (text) {
                res.write(JSON.stringify({ type: "delta", text }) + "\n");
            }

            if (choice.finish_reason != null) {
                finishReason = choice.finish_reason;
            }
        }

        finished = true;
        res.write(JSON.stringify({ type: "done", finishReason }) + "\n");
        res.end();
    } catch (error) {
        finished = true;
        if (controller.signal.aborted || res.destroyed) return;

        if (!res.headersSent) {
            res.status(502).json({ error: "The model service is temporarily unavailable" });
        } else {
            res.write(JSON.stringify({ type: "error", message: "Generation interrupted" }) + "\n");
            res.end();
        }

        console.error(error);
    }
});

app.listen(3000, "127.0.0.1", () => {
    console.log("http://127.0.0.1:3000");
});

Compared with the core snippet, this adds three necessary pieces:

  • res.on("close"): Cancels the model request if the response disconnects early. finished prevents cancellation after normal completion.
  • { signal: controller.signal }: Passes the cancellation signal to the model request.
  • try...catch: Selects HTTP 502 or NDJSON error depending on whether the response has started. If the request was cancelled or res.destroyed indicates a closed connection, it stops attempting to write to the browser.

Cache-Control and X-Accel-Buffering also reduce streaming buffers introduced by some caches and proxies. They cannot guarantee character-by-character display in every network environment.


🧪 Test the Endpoint

Start the service from the project root:

node --env-file=.env 08.server.mjs

If your earlier AIHubMix requests required a local proxy, use:

HTTPS_PROXY=http://127.0.0.1:7890 NODE_USE_ENV_PROXY=1 node --env-file=.env 08.server.mjs

Open another terminal and send a question:

curl -N -X POST http://127.0.0.1:3000/api/chat \
    -H 'Content-Type: application/json' \
    -d '{"message":"Introduce Node.js in one sentence"}'

The terminal might show:

{"type":"delta","text":"Node.js"}
{"type":"delta","text":" lets JavaScript run on the server."}
{"type":"done","finishReason":"stop"}

This only illustrates the response format, rather than recording a real model call. Answer content and chunk boundaries vary. curl -N reduces curl's own output buffering so you can observe streaming.

Now send an empty message:

curl -i -X POST http://127.0.0.1:3000/api/chat \
    -H 'Content-Type: application/json' \
    -d '{"message":""}'

You should receive HTTP 400 and a JSON error without reaching the model call.

A browser can read NDJSON with fetch(). Its received chunks do not necessarily align with complete lines, so the frontend must assemble full lines before calling JSON.parse().
This example listens only on 127.0.0.1 for local learning. Before opening it to other users, add authentication, rate limits, and usage controls; otherwise, others could consume model credit through your backend endpoint.

❓ Knowledge Check

Q1: Why does curl work while a direct request from a Vue page may trigger a cross-origin error?

curl is not subject to the browser's same-origin policy. Different ports for the Vue development server and Express make the browser treat requests as cross-origin. When connecting Vue later, use a Vite development proxy to forward /api/chat. This article focuses on verifying the backend endpoint.

Q2: Why might text fail to appear character by character even after res.write()?

Model chunks vary in length, and networks, proxies, and clients can buffer data. Streaming means sending content before the entire answer is generated, rather than guaranteeing one character per write.


🧪 Exercise

Test /api/chat with a normal message and an empty one. A normal request should receive delta followed by done; an empty message should return HTTP 400.

Next, change the allowed message length from 2000 to 1000 characters, update the matching error message, and restart the service.

Use the following command to generate a message exactly 1000 characters long:

node -e 'process.stdout.write(JSON.stringify({ message: "a".repeat(Number(process.argv[1])) }))' 1000 \
    | curl -i -X POST http://127.0.0.1:3000/api/chat \
        -H 'Content-Type: application/json' --data-binary @-

Change 1000 to 1001 in the command and run it again.

Success criteria: A 1000-character message reaches the model call; a 1001-character message receives HTTP 400 directly without calling the model.

Consider this: if you collect all text chunks and call res.write() only once after generation finishes, can the browser still display the answer while it is being generated?


🎉 You have built an Express streaming endpoint that a browser can call. Next, you will save and restore chat history.