Basic JavaScript AI API Concept
You can also call AI APIs from JavaScript, whether in a Node.js backend or a web frontend. The concept is the same as Python, but the syntax differs.
8 min•By Priygop Team•Updated 2026
OpenAI API in JavaScript (Node.js)
OpenAI API in JavaScript (Node.js)
// OpenAI API call from Node.js
// Install: npm install openai
// Set environment variable: set OPENAI_API_KEY=your-key-here
import OpenAI from 'openai';
// NEVER hardcode the API key. Read from environment variables.
const client = new OpenAI({
apiKey: process.env.OPENAI_API_KEY, // Reads from environment variable
});
async function askAI(question) {
try {
const response = await client.chat.completions.create({
model: 'gpt-4o-mini',
messages: [
{
role: 'system',
content: 'You are a helpful tutor for beginners learning Generative AI.',
},
{
role: 'user',
content: question,
},
],
max_tokens: 300,
temperature: 0.7,
});
// Extract the text from the response
return response.choices[0].message.content;
} catch (error) {
// Handle errors gracefully
if (error.status === 401) {
return 'Error: Invalid API key. Check your OPENAI_API_KEY environment variable.';
}
if (error.status === 429) {
return 'Error: Rate limit reached. Please wait a moment before trying again.';
}
return `Error: ${error.message}`;
}
}
// Example usage
const question = 'What is prompt engineering?';
askAI(question).then(answer => {
console.log('Question:', question);
console.log('Answer:', answer);
});Browser vs Server Security
Warning
Never call an AI API directly from browser-side JavaScript. Your API key would be visible to anyone who views the page source. Instead, call the AI API from your server (Node.js, Python, etc.) and have your browser JavaScript call your own server. Your server then calls the AI API with the key stored securely as an environment variable.
Diagram
Loading diagram…
Deep Learning ⊂ Machine Learning ⊂ Artificial Intelligence