Building AI Features in Node.js: LLM APIs, Streaming and Tool Calling
Node.js's async, event-driven model is ideal for AI features: you spend most of the time waiting on model APIs and streaming tokens back to users. Here's a production-minded pattern.
Streaming to the Browser With SSE
import express from 'express';
import Anthropic from '@anthropic-ai/sdk';
const app = express();
app.use(express.json());
const client = new Anthropic();
app.post('/api/chat', async (req, res) => {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
const stream = client.messages.stream({
model: 'claude-sonnet-5-5', // check the provider docs for current model names
max_tokens: 1024,
messages: [{ role: 'user', content: req.body.message }],
});
stream.on('text', (text) => res.write(`data: ${JSON.stringify({ text })}\n\n`));
stream.on('end', () => { res.write('data: [DONE]\n\n'); res.end(); });
stream.on('error', () => res.end());
req.on('close', () => stream.abort());
});
The req.on('close') line stops paying for tokens nobody will read when the user leaves.
Structured Output
For backend logic, ask for JSON and validate it:
import { z } from 'zod';
const Triage = z.object({
category: z.enum(['billing', 'bug', 'feature', 'other']),
priority: z.enum(['low', 'medium', 'high']),
summary: z.string().max(200),
});
// Parse the model's JSON with Triage.parse(...) and handle failures
Use the provider's structured output or tool-use features to make valid JSON far more reliable.
Tool Calling
Give the model functions it can request:
- Define tools with JSON schemas (e.g.
get_order_status) - The model replies with a tool-use request
- Your Node code runs the function (with auth checks!)
- Send the result back; the model writes the final answer
Production Checklist
- Timeouts and retries with backoff for 429 and 5xx errors
- Rate limiting per user to control cost and abuse
- Log token usage per request and feature
- Never trust model output to make security decisions
- Prompt injection awareness — user content and retrieved documents can contain instructions
- Observability — trace model calls (OpenTelemetry, New Relic AI Monitoring)
- Keep API keys server-side, never in frontend code
The AI call is three lines. The production work — streaming, validation, limits, and monitoring — is where Node.js engineers add real value.