mastra-ai/mastra · error · Error

Could not find API key process.env.${envVarDisplay} for mode

Error message

Could not find API key process.env.${envVarDisplay} for model id ${modelId}

What it means

The ModelsDev gateway's getApiKey() resolves the provider's API key from environment variables listed in the provider's apiKeyEnvVar config (a single name or an array of alternates). When resolveApiKeyFromEnv finds none of them set, it throws this error naming the expected env var(s) and the model id. It exists so model resolution fails fast with a clear message instead of sending unauthenticated requests.

Source

Thrown at packages/core/src/llm/model/gateways/models-dev.ts:325

    return customBaseUrl || interpolateUrlTemplate(template, envVars);
  }

  getApiKey(modelId: string): Promise<string> {
    const [provider, model] = modelId.split('/');
    if (!provider || !model) {
      throw new Error(`Could not identify provider from model id ${modelId}`);
    }
    const config = this.providerConfigs[provider];

    if (!config) {
      throw new Error(`Could not find config for provider ${provider} with model id ${modelId}`);
    }

    const apiKey = resolveApiKeyFromEnv(config.apiKeyEnvVar);

    if (!apiKey) {
      const envVarDisplay = Array.isArray(config.apiKeyEnvVar) ? config.apiKeyEnvVar.join(' or ') : config.apiKeyEnvVar;
      throw new Error(`Could not find API key process.env.${envVarDisplay} for model id ${modelId}`);
    }

    return Promise.resolve(apiKey);
  }

  async resolveLanguageModel({
    modelId,
    providerId,
    apiKey,
    headers,
  }: {
    modelId: string;
    providerId: string;
    apiKey: string;
    headers?: Record<string, string>;
  }): Promise<GatewayLanguageModel> {
    const baseURL = this.buildUrl(`${providerId}/${modelId}`);

View on GitHub (pinned to 75dd419e61)

Solutions

  1. Set the env var named in the message (or any one of the listed alternates) before starting the app: export OPENAI_API_KEY=... or put it in .env and ensure dotenv is loaded at startup.
  2. Verify the variable is actually visible to the process: add a startup check like if (!process.env.OPENAI_API_KEY) throw ... or log Object.keys(process.env) in CI/serverless.
  3. If the key is set under a different name, check whether the gateway supports a custom apiKeyEnvVar / provider config override and point it at your var.
  4. If you pass an explicit API key via provider options instead of env, confirm you're using the code path that accepts it (e.g. Mastra model config with apiKey) so getApiKey's env lookup isn't reached.

Example fix

// before
const agent = new Agent({ name: 'a', model: 'openai/gpt-4o' });
// after (ensure the key exists before constructing/running)
import 'dotenv/config';
if (!process.env.OPENAI_API_KEY) {
  throw new Error('OPENAI_API_KEY is required for openai/gpt-4o');
}
const agent = new Agent({ name: 'a', model: 'openai/gpt-4o' });
Defensive patterns

Strategy: validation

Validate before calling

function requireEnv(name: string | string[]) {
  const vars = Array.isArray(name) ? name : [name];
  const found = vars.find(v => process.env[v]);
  if (!found) throw new Error(`Missing required env var: ${vars.join(' or ')}`);
  return process.env[found]!;
}
requireEnv('OPENAI_API_KEY'); // call before creating/using the model

Type guard

function hasApiKey(vars: string[], env: NodeJS.ProcessEnv = process.env): env is NodeJS.ProcessEnv & Record<string, string> {
  return vars.some(v => typeof env[v] === 'string' && env[v].length > 0);
}

Try / catch

try {
  const agent = new Agent({ model: 'openai/gpt-4o' });
} catch (e) {
  if (e instanceof Error && e.message.includes('Could not find API key')) {
    console.error('Set the provider API key env var:', e.message);
    process.exit(1);
  }
  throw e;
}

Prevention

When it happens

Trigger: Calling getApiKey(modelId) (directly or via gateway model resolution, e.g. agent('provider/model')) when none of process.env entries in config.apiKeyEnvVar for the provider are set. E.g. using 'openai/gpt-4o' without OPENAI_API_KEY, or 'netlify/...' without NETLIFY_TOKEN/NETLIFY_SITE_ID.

Common situations: Forgetting to load a .env file (no dotenv call, or .env in the wrong directory); setting the var in the shell but running under a service manager/CI that doesn't inherit it; deploying to serverless where secrets were never added; a typo'd env var name; switching providers and reusing the old key var; the provider requiring one of several vars but none set.

Understand the failure class

Background: "environment variable is not set" and "Missing keys in environment" errors: what missing required env var messages mean and how to fix them — this error's family across 28 libraries.

Related errors


AI-assisted analysis of mastra-ai/mastra@75dd419e61 (2026-08-30). Data as JSON: /api/errors/2398039a096da285. Report an issue: GitHub.