mastra-ai/mastra · error · MastraError

MASTRA_GATEWAY_NO_API_KEY

MASTRA_GATEWAY_NO_API_KEY

Error message

Missing MASTRA_GATEWAY_API_KEY environment variable

What it means

The Mastra gateway requires an API key to authenticate requests, and none was found. getApiKey checks config.apiKey first, then the MASTRA_GATEWAY_API_KEY environment variable; if both are empty the gateway cannot authenticate and throws. This MastraError indicates missing credentials configuration.

Source

Thrown at packages/core/src/llm/model/gateways/mastra.ts:77

        apiKeyHeader: 'Authorization',
        name: 'Gateway',
        gateway: 'mastra',
        models: [...models],
        docUrl: 'https://mastra.ai/docs/gateway',
      },
    };

    return providers;
  }

  async buildUrl(_modelId: string): Promise<string> {
    return `${this.getBaseUrl()}/v1`;
  }

  async getApiKey(): Promise<string> {
    const apiKey = this.config?.apiKey ?? process.env['MASTRA_GATEWAY_API_KEY'];
    if (!apiKey) {
      throw new MastraError({
        id: 'MASTRA_GATEWAY_NO_API_KEY',
        domain: 'LLM',
        category: 'UNKNOWN',
        text: 'Missing MASTRA_GATEWAY_API_KEY environment variable',
      });
    }
    return apiKey;
  }

  resolveLanguageModel({
    modelId,
    providerId,
    apiKey,
    headers,
  }: {
    modelId: string;
    providerId: string;
    apiKey: string;

View on GitHub (pinned to 75dd419e61)

Solutions

  1. Set MASTRA_GATEWAY_API_KEY in the environment before making requests.
  2. Pass the key explicitly: new MastraGateway({ apiKey: process.env.MASTRA_GATEWAY_API_KEY }).
  3. Verify .env loading (dotenv/Next.js env handling) and variable spelling in your deployment config.
  4. Add a startup validation that fails fast if the env var is missing.

Example fix

// before
const gw = new MastraGateway({}); // no key anywhere
// after
const gw = new MastraGateway({ apiKey: process.env.MASTRA_GATEWAY_API_KEY });
// and/or in shell: export MASTRA_GATEWAY_API_KEY=...
Defensive patterns

Strategy: validation

Validate before calling

if (!process.env.MASTRA_GATEWAY_API_KEY) {
  throw new Error('MASTRA_GATEWAY_API_KEY must be set before creating/using the Mastra gateway');
}

Prevention

When it happens

Trigger: Calling getApiKey() (during model resolution/requests) when the MastraGateway was constructed without config.apiKey and process.env.MASTRA_GATEWAY_API_KEY is unset.

Common situations: Deploying to an environment where the env var wasn't set; .env file not loaded; variable renamed or typo'd; constructing gateway with an empty config object.

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/6592268ecf8a1e16. Report an issue: GitHub.