mastra-ai/mastra · error · Error

Invalid ENV key: ${key}

Error message

Invalid ENV key: ${key}

What it means

FileEnvService.validateEnvEntry throws this when an environment variable key being written to a .env file does not match ^[A-Za-z_][A-Za-z0-9_]*$. Keys must start with a letter or underscore and contain only letters, digits, and underscores, since .env files are simple KEY=VALUE text parsed by shell-compatible tooling. This guard prevents writing an unparseable or dangerous entry into the env file.

Source

Thrown at packages/cli/src/services/service.env.ts:19

import * as fs from 'node:fs/promises';

export abstract class EnvService {
  abstract getEnvValue(key: string): Promise<string | null>;
  abstract setEnvValue(key: string, value: string): Promise<void>;
}

function escapeRegExp(value: string): string {
  return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

export class FileEnvService extends EnvService {
  private static readonly ENV_KEY_REGEX = /^[A-Za-z_][A-Za-z0-9_]*$/;

  private readonly filePath: string;

  private validateEnvEntry(key: string, value: string): void {
    if (!FileEnvService.ENV_KEY_REGEX.test(key)) {
      throw new Error(`Invalid ENV key: ${key}`);
    }
    if (/[\r\n]/.test(value)) {
      throw new Error(`Invalid ENV value for ${key}: multiline values are not supported.`);
    }
  }

  constructor(filePath: string) {
    super();
    this.filePath = filePath;
  }

  private envLineRegex(key: string, captureValue = false): RegExp {
    const pattern = captureValue ? `^${escapeRegExp(key)}=(.*)$` : `^${escapeRegExp(key)}=.*$`;
    return new RegExp(pattern, 'm');
  }

  private async updateEnvData({
    key,

View on GitHub (pinned to 75dd419e61)

Solutions

  1. Rename the key to uppercase snake_case, e.g. my-key -> MY_KEY
  2. Strip invalid characters and sanitize before writing: key.replace(/[^A-Za-z0-9_]/g, '_').replace(/^[0-9]+/, '')
  3. Ensure the key is non-empty and does not embed '=' or whitespace
  4. Validate keys with the same regex in your own code before calling updateEnvData

Example fix

// before
await service.updateEnvData({ 'my-key': 'value' });
// after
await service.updateEnvData({ MY_KEY: 'value' });
Defensive patterns

Strategy: validation

Validate before calling

const ENV_KEY_REGEX = /^[A-Za-z_][A-Za-z0-9_]*$/;
function assertValidEnvKey(key: string) {
  if (!ENV_KEY_REGEX.test(key)) throw new Error(`Invalid ENV key: ${key}`);
}

Type guard

const isValidEnvKey = (key: string): boolean => /^[A-Za-z_][A-Za-z0-9_]*$/.test(key);

Try / catch

try {
  await service.updateEnvData(entries);
} catch (e) {
  if (e instanceof Error && e.message.startsWith('Invalid ENV key')) {
    console.error(`Fix key format (must match ^[A-Za-z_][A-Za-z0-9_]*$): ${e.message}`);
  } else throw e;
}

Prevention

When it happens

Trigger: Calling updateEnvData (which delegates to validateEnvEntry) with a key containing hyphens, dots, spaces, leading digits, an '=' sign, or an empty string — e.g. programmatic writes like envService.updateEnvData({ 'my-key': 'v' }) or keys derived from untrusted input.

Common situations: Migrating config that used hyphenated names (my-key) instead of env-style names (MY_KEY); injecting user-supplied keys without sanitizing; accidentally passing a whole 'KEY=value' string as the key; empty key from a bad split.

Related errors


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