DeepSeek API Node.js Tutorial — Streaming, TypeScript & Production

May 19, 2026 · 6 min read · NovAI Blog

This guide covers everything you need to use DeepSeek API from Node.js — basic chat, streaming, TypeScript types, Express SSE integration, function calling, and production error handling.

All examples work with any OpenAI-compatible API. Just swap the base URL and model name.

1. Basic Chat Completion

import OpenAI from 'openai';

const client = new OpenAI({
  baseURL: 'https://aiapi-pro.com/v1',
  apiKey: process.env.NOVAI_API_KEY,
});

const response = await client.chat.completions.create({
  model: 'deepseek-chat',
  messages: [
    { role: 'system', content: 'You are a helpful assistant.' },
    { role: 'user', content: 'Write a TypeScript function to merge two sorted arrays.' },
  ],
});

console.log(response.choices[0].message.content);

2. Streaming (SSE)

const stream = await client.chat.completions.create({
  model: 'deepseek-chat',
  messages: [{ role: 'user', content: 'Explain async/await in 3 sentences.' }],
  stream: true,
});

for await (const chunk of stream) {
  process.stdout.write(chunk.choices[0]?.delta?.content || '');
}

3. Express SSE Endpoint

Try this model free

$5 credit for new users · No card required · OpenAI-compatible API

Start Free →
import express from 'express';
import OpenAI from 'openai';

const app = express();
const client = new OpenAI({
  baseURL: 'https://aiapi-pro.com/v1',
  apiKey: process.env.NOVAI_API_KEY,
});

app.post('/chat', async (req, res) => {
  res.setHeader('Content-Type', 'text/event-stream');
  res.setHeader('Cache-Control', 'no-cache');
  res.setHeader('Connection', 'keep-alive');

  const stream = await client.chat.completions.create({
    model: 'deepseek-chat',
    messages: req.body.messages,
    stream: true,
  });

  for await (const chunk of stream) {
    const text = chunk.choices[0]?.delta?.content || '';
    if (text) res.write(`data: ${JSON.stringify({ text })}\n\n`);
  }
  res.write('data: [DONE]\n\n');
  res.end();
});

app.listen(3000);

4. TypeScript Types

interface ChatMessage {
  role: 'system' | 'user' | 'assistant';
  content: string;
}

interface StreamChunk {
  choices: Array<{
    delta: { content?: string };
    finish_reason: 'stop' | 'length' | null;
  }>;
}

async function* streamChat(
  messages: ChatMessage[]
): AsyncGenerator {
  const stream = await client.chat.completions.create({
    model: 'deepseek-chat',
    messages,
    stream: true,
  });
  for await (const chunk of stream) {
    const text = (chunk as StreamChunk).choices[0]?.delta?.content;
    if (text) yield text;
  }
}

5. Error Handling

async function chatWithRetry(messages, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await client.chat.completions.create({
        model: 'deepseek-chat',
        messages,
      });
    } catch (err) {
      if (err.status === 429) {
        const wait = Math.pow(2, i) * 1000;
        console.log(`Rate limited, retrying in ${wait}ms...`);
        await new Promise(r => setTimeout(r, wait));
        continue;
      }
      if (err.status === 402) {
        throw new Error('Insufficient balance — top up at aiapi-pro.com');
      }
      throw err;
    }
  }
  throw new Error('Max retries exceeded');
}

6. Function Calling

const response = await client.chat.completions.create({
  model: 'deepseek-chat',
  messages: [{ role: 'user', content: 'What is the weather in Tokyo?' }],
  tools: [{
    type: 'function',
    function: {
      name: 'get_weather',
      description: 'Get weather for a city',
      parameters: {
        type: 'object',
        properties: {
          city: { type: 'string' },
        },
        required: ['city'],
      },
    },
  }],
});
Tip: deepseek-v4-vs-gpt-5-5-2026" style="color:#0284c7;text-decoration:underline">DeepSeek V4 Flash costs $0.14/1M input via NovAI — about 35x cheaper than GPT-4o for the same code. The API is fully OpenAI-compatible, so SDKs like LangChain, Vercel AI SDK, and LlamaIndex work out of the box.

Try DeepSeek from Node.js — $5.00 free credit

Just change base URL to https://aiapi-pro.com/v1. No Chinese phone needed. USDT (TRC20).

→ Get API Key Free

Ready to build? Get $5 free credit

OpenAI-compatible API — just change base_url and your API key

Start Free →
Zhipu AI Ecosystem Partner Volcano Engine Ecosystem Partner Tencent Cloud Ecosystem Partner

🚀 Start Using AI APIs for Free

Sign up now and get $5.00 free credit — access DeepSeek, Qwen, GLM, Doubao and more. No credit card required.

Get Free $2 Credit →

Already have an account? Log in here