yarnpkg/yarn · error · Error

Failed to replace env in config: ${match}

Error message

Failed to replace env in config: ${match}

What it means

envReplace() substitutes ${VAR} and $VAR patterns in config values. If a referenced environment variable is undefined, it throws rather than silently leaving a broken value. This guards configs from silently deploying with unexpanded placeholders.

Source

Thrown at src/util/env-replace.js:16

/* @flow */
const ENV_EXPR = /(\\*)\$\{([^}]+)\}/g;

export type Env = {[key: string]: ?string};

export default function envReplace(value: string, env: Env = process.env): string {
  if (typeof value !== 'string' || !value) {
    return value;
  }

  return value.replace(ENV_EXPR, (match: string, esc: string, envVarName: string) => {
    if (esc.length && esc.length % 2) {
      return match;
    }
    if (undefined === env[envVarName]) {
      throw new Error('Failed to replace env in config: ' + match);
    }
    return env[envVarName] || '';
  });
}

View on GitHub (pinned to c2dda503f3)

Solutions

  1. Set the referenced environment variable in your shell or CI configuration
  2. Remove or correct the ${VAR} reference in the config file
  3. Provide a default value in a wrapper script before running Yarn

Example fix

# before (.npmrc)
//registry.npmjs.org/:_authToken=${NPM_TOKEN}
# after — export the var first
export NPM_TOKEN=xxxxx
Defensive patterns

Strategy: validation

Validate before calling

function envVarsReferenced(value: string): string[] {
  const matches = value.match(/\$\{(\w+)\}|\$(\w+)/g) || [];
  return matches.map(m => m.replace(/[${}]/g, ''));
}
const missing = envVarsReferenced(configValue).filter(v => !(v in process.env));
if (missing.length) {
  throw new Error(`Unset env vars referenced in config: ${missing.join(', ')}`);
}

Type guard

function allEnvVarsDefined(value: string, env: object): boolean {
  const re = /\$\{(\w+)\}|\$(\w+)/g;
  let m;
  while ((m = re.exec(value))) {
    const name = m[1] || m[2];
    if (!(name in env)) return false;
  }
  return true;
}

Try / catch

try {
  const replaced = envReplace(value);
} catch (e) {
  if (e.message.includes('Failed to replace env')) {
    // substitute a default or prompt the user to set the var
  }
}

Prevention

When it happens

Trigger: A config value (e.g., in .npmrc) references an env var via ${VAR} or $VAR that is not set in the current environment. ENV_EXPR matches but env[envVarName] is undefined.

Common situations: CI without the expected env var; configs shared between machines with different env setups; typo in the variable name; escaped backslashes producing an unexpected match.

Related errors


AI-assisted analysis of yarnpkg/yarn@c2dda503f3 (2026-08-13). Data as JSON: /api/errors/b92dcb92b751036e. Report an issue: GitHub.