Getting Started with the OpenAI API in Node.js

The OpenAI API brought large language models to application developers through a simple HTTP interface. Node.js remains a natural fit for BFF layers that call LLMs.

Installation and First Request

npm install openai
import OpenAI from 'openai';

const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

const completion = await client.chat.completions.create({
  model: 'gpt-4',
  messages: [
    { role: 'system', content: 'You are a helpful coding assistant.' },
    { role: 'user', content: 'Explain async/await in JavaScript.' },
  ],
});

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

Production Considerations

Never expose API keys in frontend bundles. Proxy requests through your backend. Set max_tokens, timeouts, and retry policies. Log token usage for cost control.

Streaming

Use stream: true for chat UIs that render tokens as they arrive-better perceived latency than waiting for the full response.

Conclusion

The OpenAI API is the fastest path to LLM features in a Node stack. Layer prompt templates, validation, and observability on top from day one.