How to Fix 'invalid API key during development' in CrewAI (TypeScript)

By Cyprian AaronsUpdated 2026-04-21
invalid-api-key-during-developmentcrewaitypescript

When CrewAI throws invalid API key during development, it usually means the SDK tried to initialize a provider client with an empty, malformed, or unavailable key. In TypeScript projects, this often shows up during local runs, tests, or when your .env file is loaded too late.

The error is rarely “CrewAI is broken.” It’s almost always config timing, env loading, or passing the wrong key to the wrong provider.

The Most Common Cause

The #1 cause is reading process.env before your environment variables are loaded. In TypeScript apps, this happens when you import and instantiate OpenAI, Anthropic, or a CrewAI agent at module scope before dotenv.config() runs.

Here’s the broken pattern:

// src/crew.ts
import { Agent } from "crewai";
import { OpenAI } from "openai";
import dotenv from "dotenv";

// Too late: env vars are read before config runs
const llm = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
});

dotenv.config();

export const supportAgent = new Agent({
  role: "Support Engineer",
  goal: "Resolve customer issues",
  backstory: "You handle banking support tickets",
  llm,
});

And here’s the fixed pattern:

// src/crew.ts
import dotenv from "dotenv";
dotenv.config();

import { Agent } from "crewai";
import { OpenAI } from "openai";

const apiKey = process.env.OPENAI_API_KEY;

if (!apiKey) {
  throw new Error("Missing OPENAI_API_KEY");
}

const llm = new OpenAI({
  apiKey,
});

export const supportAgent = new Agent({
  role: "Support Engineer",
  goal: "Resolve customer issues",
  backstory: "You handle banking support tickets",
  llm,
});

The important part is not just dotenv.config(). It’s making sure the env var exists before you construct the client. If you see errors like:

  • Error: Invalid API key
  • 401 Unauthorized
  • OpenAIError: The api_key client option must be set
  • CrewAIError: invalid API key during development

then this is the first place to look.

Other Possible Causes

1. You’re using the wrong environment variable name

A lot of people set CREWAI_API_KEY and expect it to work everywhere. CrewAI agents usually depend on the underlying model provider key, such as OPENAI_API_KEY, ANTHROPIC_API_KEY, or GOOGLE_API_KEY.

# Broken
CREWAI_API_KEY=sk-xxxx

# Fixed
OPENAI_API_KEY=sk-xxxx

If your code uses OpenAI under the hood, setting only a Crew-specific variable won’t help.

2. You passed a placeholder value from local dev settings

This happens when .env.local contains a fake key or your test runner injects a dummy value.

// Broken
const llm = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY || "your-api-key-here",
});

Use fail-fast validation instead:

// Fixed
const apiKey = process.env.OPENAI_API_KEY;

if (!apiKey || apiKey === "your-api-key-here") {
  throw new Error("OPENAI_API_KEY is missing or invalid");
}

If you let placeholder strings reach the SDK, you’ll get confusing auth failures that look like provider issues but are really config bugs.

3. Your .env file is not being loaded in the runtime you’re using

This shows up in Bun, ts-node, Vitest, Jest, or Next.js where execution context differs from plain Node.js.

{
  "scripts": {
    "dev": "ts-node src/index.ts"
  }
}

If dotenv.config() isn’t executed in that entrypoint, your app sees undefined.

Fix it by loading env vars at the actual runtime boundary:

// src/index.ts
import dotenv from "dotenv";
dotenv.config();

import "./app";

For test runners, configure setup files instead of relying on imports buried deep in your app.

4. You’re mixing providers and keys

If you configure an Anthropic model with an OpenAI key, auth fails immediately.

// Broken
import { Anthropic } from "@anthropic-ai/sdk";

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

Use the matching provider key:

// Fixed
const client = new Anthropic({
  apiKey: process.env.ANTHROPIC_API_KEY,
});

This is common when switching models inside CrewAI and reusing old environment variables without updating the code path.

How to Debug It

  1. Print the resolved value before constructing CrewAI objects
    • Check whether it’s undefined, empty, or a placeholder.
    • Do not print full secrets; log only presence and length.
console.log("OPENAI_API_KEY present:", Boolean(process.env.OPENAI_API_KEY));
console.log("OPENAI_API_KEY length:", process.env.OPENAI_API_KEY?.length ?? 0);
  1. Verify env loading happens before imports that create clients

    • If a module instantiates an LLM at import time, move initialization into a function.
    • This avoids “works in one file, fails in another” behavior.
  2. Confirm provider/key pairing

    • OpenAI client → OPENAI_API_KEY
    • Anthropic client → ANTHROPIC_API_KEY
    • Google/Gemini client → provider-specific Google key
  3. Run a minimal auth check outside CrewAI

    • If raw SDK auth fails, CrewAI will fail too.
    • Test the provider directly with one request before wiring it into agents.

Prevention

  • Load environment variables at app startup, not inside random modules.
  • Fail fast if required keys are missing or obviously fake.
  • Keep one .env.example per project with exact variable names for each provider.
  • Avoid module-scope agent/client construction unless env loading is guaranteed first.

If you’re building CrewAI systems for banking or insurance workflows, treat API keys like any other production dependency. Validate them early, wire them explicitly, and never assume your local shell matches your runtime.


Keep learning

By Cyprian Aarons, AI Consultant at Topiax.

Want the complete 8-step roadmap?

Grab the free AI Agent Starter Kit — architecture templates, compliance checklists, and a 7-email deep-dive course.

Get the Starter Kit

Related Guides