I’m having trouble setting up the OpenAI library in my Node.js project
I keep getting a constructor error when I try to create an OpenAI client instance. I’m pretty new to JavaScript development so any help would be great.
My current code:
require('dotenv').config();
const { OpenAI } = require('openai');
// Create OpenAI client using API key from environment
const aiClient = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
/**
* Creates a chat completion using GPT model
* @param {string} prompt - User message
* @returns {Promise<string>} - AI response
*/
async function getChatResponse(prompt) {
try {
console.log('Making request to OpenAI:', prompt);
const completion = await aiClient.chat.completions.create({
model: "gpt-4",
messages: [{
role: "user",
content: prompt
}],
});
if (completion.choices && completion.choices.length > 0) {
console.log('Got response from API');
return completion.choices[0].message.content;
} else {
console.log('Empty response received');
throw new Error('Empty response from API');
}
} catch (err) {
console.error('API request failed:', err.message);
throw err;
}
}
module.exports = { getChatResponse };
The error I’m getting:
TypeError: OpenAI is not a constructor
at Object.<anonymous> (C:\projects\my-bot\aiService.js:4:18)
at Module._compile (node:internal/modules/cjs/loader:1376:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1435:10)
I’ve tried different import methods but nothing seems to work. What am I doing wrong here?
check if u installed the wrong package - there are 3 different OpenAI npm packages out there. run npm ls openai to see what u actually have. people often grab @openai/api or openai-api instead of the official “openai” package, which causes these constructor errors.
Had the same issue last week - check if you’re mixing import syntaxes. Sometimes npm gives you CommonJS when you expect ES modules or vice versa. Try const OpenAI = require('openai') without the brackets first, that usually fixes constructor errors.
This is a version mismatch issue. You’re using v4 destructuring syntax, but the constructor error means you’ve got an older version installed. Check your version with npm list openai first. If it’s v3.x, either upgrade with npm install openai@latest or switch your import to const { Configuration, OpenAIApi } = require('openai') and configure it the old way. I hit this same problem when they updated - v4 completely changed how initialization works compared to v3.
This constructor error usually means there’s a mismatch between your import and what’s actually exported. I’ve seen this tons of times - it’s often cached node_modules or mixed package versions causing trouble. Delete your node_modules folder and package-lock.json, then run npm install again. Check your package.json for the openai version too. If you see “^3.3.0” but you’re using v4 syntax, there’s your problem. OpenAI’s package had massive breaking changes between versions and completely restructured imports.
This constructor error usually means your environment variable isn’t loading right or there’s something wrong with how the OpenAI class gets resolved. I’ve hit this before when my API key wasn’t set up correctly - the library can’t initialize the constructor when it can’t validate the key format. Check that your .env file is in the root directory and OPENAI_API_KEY doesn’t have extra spaces or quotes. Also verify the key’s actually loading by adding console.log(process.env.OPENAI_API_KEY) before the constructor call. If that shows undefined, it’s your dotenv config that’s broken, not the import syntax.