How to beginner · 3 min read

How to call OpenAI API from JavaScript

Quick answer
Use the official openai JavaScript SDK by installing it via npm, setting your API key in environment variables, and calling client.chat.completions.create() with your desired model and messages. This approach ensures secure, efficient access to OpenAI models like gpt-4o.

PREREQUISITES

  • Node.js 18+
  • OpenAI API key (free tier works)
  • npm install openai

Setup

Install the official OpenAI JavaScript SDK and set your API key as an environment variable for secure access.

bash
npm install openai

Step by step

This example demonstrates a complete, runnable Node.js script that calls the OpenAI API to generate a chat completion using the gpt-4o model.

javascript
import { config } from 'dotenv';
config();

import { OpenAI } from 'openai';

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

async function run() {
  const response = await client.chat.completions.create({
    model: 'gpt-4o',
    messages: [
      { role: 'user', content: 'Hello, how do I call the OpenAI API from JavaScript?' }
    ]
  });
  console.log(response.choices[0].message.content);
}

run();
output
Hello! To call the OpenAI API from JavaScript, use the official OpenAI SDK, set your API key in environment variables, and invoke the chat completion endpoint as shown.

Common variations

You can use async/await or promise syntax, switch models like gpt-4o-mini, or stream responses for real-time output. The SDK supports all these patterns.

javascript
import { OpenAI } from 'openai';
const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

// Using promises
client.chat.completions.create({
  model: 'gpt-4o-mini',
  messages: [{ role: 'user', content: 'Tell me a joke.' }]
}).then(response => {
  console.log(response.choices[0].message.content);
});
output
Why did the developer go broke? Because he used up all his cache!

Troubleshooting

  • If you get an authentication error, verify your OPENAI_API_KEY is set correctly in your environment.
  • For network errors, check your internet connection and firewall settings.
  • If the model name is invalid, confirm you are using a current model like gpt-4o or gpt-4o-mini.

Key Takeaways

  • Use the official OpenAI JavaScript SDK installed via npm for best compatibility.
  • Always store your API key securely in environment variables, never hardcode it.
  • Call client.chat.completions.create() with the model and messages to get chat completions.
  • You can switch models or use streaming easily with the same SDK methods.
  • Check environment setup and model names if you encounter errors.
Verified 2026-04 · gpt-4o, gpt-4o-mini
Verify ↗