1

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,
    };
  },
};

2 Answers 2

0

The "Missing credentials" error occurs because the process.env.OPENAI_API_KEY is likely undefined at runtime, meaning your .env file isn't being loaded properly by dotenv. Ensure you import and call dotenv.config() early in your application entry point (e.g., app.ts or index.ts) before any modules that use the OpenAI client are imported or initialized. Also, verify your .env file is in the project root, contains OPENAI_API_KEY=your_actual_key (no quotes, no spaces), and isn't ignored by .gitignore. If using TypeScript, confirm dotenv is installed (npm i dotenv and npm i -D @types/node if needed).


// .env file (project root, not committed to repo)
OPENAI_API_KEY = sk - your - actual - key - here
// app.ts or index.ts (entry point)
import dotenv from 'dotenv';
dotenv.config();  // Load early, before OpenAI imports
import OpenAI from 'openai';
const openAIClient = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
// To debug: console.log('API Key loaded:', !!process.env.OPENAI_API_KEY); // Should log true if loaded
type GenerateTextOptions = {
  model?: string;
  prompt: string;
  instructions?: string;  // Use system message for instructions
  temperature?: number;
  maxTokens?: number;
  previousResponseId?: string;  // Not standard; consider session handling
};
type GenerateTextResult = { id: string; text: string };
export const llmClient = {
  async generateText({
    model = 'gpt-3.5-turbo',
    prompt,
    instructions,
    temperature = 0.2,
    maxTokens = 300,
    previousResponseId,  // Ignored in this example; implement if needed
  }: GenerateTextOptions): Promise & lt;GenerateTextResult& gt; {
  const messages = [
    ...(instructions ? [{ role: 'system', content: instructions }] : []),
    { role: 'user', content: prompt },
  ];
  const response = await openAIClient.chat.completions.create({
    model,
    messages,
    temperature,
    max_tokens: maxTokens,
  });
  return {
    id: response.id || '',
    text: response.choices[0]?.message?.content || '',
  };
},
};

Sign up to request clarification or add additional context in comments.

2 Comments

You are right in import dot env config. But you really aware expose envs in github?. You should add .env in .gitignore
Side note, if you're using any current version of Node.js, passing a --env-file has replaced dotenv. nodejs.org/docs/latest/api/environment_variables.html#env-files
0

You can also try https://varlock.dev for an alternative to dotenv that will also give you validation and type safety. This will help ensure that env vars are all valid before anything else happens.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.