I’m building an app with NodeJs, Express and TypeScript.
At first, I hardcoded the OPENAI_API_KEY directly in my code for testing, and it worked fine.
Now, I’ve moved the key to a .env file because I want to push the code to a repo, but I’m getting this error: OpenAIError: Missing credentials. Please pass an apiKey, or set the OPENAI_API_KEY environment variable.
I tried moving my hardcoded API key into a .env file and used dotenv to load it.
I expected the OpenAI client to read the key from process.env.OPENAI_API_KEY and work normally.
Instead, I got the error:Missing credentials. Please pass an apiKey, or set the OPENAI_API_KEY environment variable.
import OpenAI from "openai";
const openAIClient = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
type GenerateTextOptions = {
model?: string;
prompt: string;
instructions?: string;
temperature?: number;
maxTokens?: number;
previousResponseId?: string;
};
type GenerateTextResult = {
id: string;
text: string;
};
export const llmClient = {
async generateText({
model = "gpt-4.1",
prompt,
instructions,
temperature = 0.2,
maxTokens = 300,
previousResponseId,
}: GenerateTextOptions): Promise<GenerateTextResult> {
const response = await openAIClient.responses.create({
model,
input: prompt,
instructions,
temperature,
max_output_tokens: maxTokens,
previous_response_id: previousResponseId,
});
return {
id: response.id,
text: response.output_text,
};
},
};