All Articles Claude Code

Environment-Specific Hook Configurations

You know that moment when you're running a hook locally and you think, "I wish this would just chill out and let me experiment"?

You know that moment when you’re running a hook locally and you think, “I wish this would just chill out and let me experiment”? Then you move to production and suddenly you need that same hook to be paranoid, blocking half your operations? That’s the whole point of environment-specific hook configurations. You need different rules for different contexts, enforced automatically based on where the code is running.

Most teams start with one-size-fits-all hooks. They work until they don’t—usually around 2 AM on a Friday when you’ve pushed stricter governance to production and your local development grinds to a halt because you can’t even test basic workflows. The fix is exactly what you’d expect: different rules for different environments, smart loading based on where the code runs. This article shows you how to build hooks that understand their environment and adapt automatically.

Why One-Size-Fits-All Fails

Here’s the reality: your local development environment and your production repository have wildly different needs. In development, you want to experiment, try risky refactors, maybe push broken commits temporarily while you’re debugging. You need your hooks to be permissive—they should catch obvious mistakes but let you iterate fast. You’re optimizing for velocity and exploration.

Production is the opposite. You want hooks screaming at you before anything ships. Commit message requirements, branch protections, mandatory PR reviews—all of it gets tighter. You can’t afford “I’ll fix it later” in production. You need guarantees that code is safe, formatted correctly, and documented properly. You’re optimizing for safety and compliance.

The thing is, the same hook logic often makes sense in both places. You’re not inventing new rules; you’re just adjusting how strictly they apply. That’s why environment-specific configs are powerful—they let you share the core hook code but layer on environment-specific behavior. The validation logic lives in one place. The configuration lives in separate files. When you need to change how strict the rules are, you update a config file, not the hook code.

Most teams cobble this together in messy ways: they either duplicate their hooks (maintenance nightmare) or they use environment detection inside their hooks (which usually gets messy fast). We’re going to show you the clean approach that scales across your entire organization.

The Cost of Rigidity

Think about what happens when you enforce production-level strictness on your development environment. Your developers are writing commit messages. The first one fails because it’s only nine characters and you require twenty. The second one passes the length check but fails because it doesn’t follow conventional commits format. By the third attempt, your developers are frustrated and asking “Why are we spending time fighting with tooling instead of writing code?”

This friction compounds across a team. A junior developer takes three times longer to commit because they keep hitting validation errors. A senior developer gets annoyed and finds ways to bypass the hooks (which defeats the entire purpose). What you wanted was a safety system. What you got was a productivity killer in development and likely-avoided-in-staging guardrails that were supposed to catch problems.

On the flip side, what happens if you keep development’s loose rules in production? Someone commits “WIP: testing” as the message. Another developer commits code that references a feature branch that got deleted. Someone else commits directly to main with no review because the local hooks don’t prevent it. By the time issues reach production, they’ve propagated through CI/CD, passed through QA (if you have it), and are already damaging systems. You wanted flexibility in development. What you got was chaos in production.

The answer isn’t choosing one extreme or the other. It’s having different rules for different contexts, applied intelligently based on where the code is running. Your development hooks are permissive because you’re optimizing for learning and experimentation. Your staging hooks are moderately strict because you’re getting ready for production. Your production hooks are locked down because any mistake has real consequences.

Why Configuration-Based Environments Win

The old-school approach was hardcoding environment checks inside hook logic. You’d see code that checks if NODE_ENV is ‘production’ and applies strict validation only then. This works, but it scales poorly. Add a third environment (staging)? Your hooks get more complex. Add a fourth requirement that staging needs? Now you’re editing hook code instead of configuration. Add a fifth team member who wants to customize behavior for their local environment? You’re back to duplicating hooks or adding more environment checks.

Configuration-driven environments are different. Your hooks load a config file based on the detected environment. That config file specifies the rules. When you need different rules, you create a new config file. When you need to update rules, you edit JSON, not JavaScript. This separation of concerns—logic in code, configuration in files—is exactly what makes systems maintainable at scale.

The other advantage is visibility. When you look at your config directory, you can instantly see “Oh, production requires conventional commits, staging requires them, development doesn’t.” You can compare side-by-side and understand the progressively stricter requirements. With logic scattered through code, that understanding takes investigation.

How Environment Detection Works in Claude Code Hooks

When a hook runs, it has access to environment information through Node.js and the hook system itself. You can detect which environment you’re in through:

  1. Environment variables set by Claude Code or your CI system—explicit and fast
  2. Repository metadata (the .git/config file tells you a lot about where you are)
  3. Branch naming patterns (if you follow conventions, branch names encode context)
  4. Git remotes (production repos often have a different origin URL structure)

The cleanest approach is using environment variables because they’re explicit, easy to control, and zero-latency. When Claude Code runs, you can set an environment variable like CLAUDE_ENV=production or CLAUDE_ENV=dev, and your hooks read that. No network calls, no parsing, just instant environment detection.

Here’s why this matters: hooks run synchronously, and they run before the actual operation completes. You can’t afford to make network calls or do slow lookups. Environment variables are instant, zero-latency checks. Your hooks complete in milliseconds, not seconds.

Setting Up Environment Variables

You control environment variables in a few places:

Locally, you typically set them in your shell:

export CLAUDE_ENV=development

Or in a .env file that your development setup loads automatically when you start work.

In CI/CD, your pipeline sets them explicitly:

# GitHub Actions example
env:
  CLAUDE_ENV: production

This ensures production hooks always run in production mode, even if someone forgets to configure their local environment.

In Docker/containers, they go in your Dockerfile or docker-compose.yml:

ENV CLAUDE_ENV=production

Claude Code respects these variables when hooks execute. The hook can read process.env.CLAUDE_ENV and adjust behavior accordingly. This is the foundation for environment-specific behavior.

Building Environment-Aware Hook Logic

Let’s build a complete, production-ready hook that demonstrates this. We’ll create a commit message validation hook that’s strict in production but relaxed in development. This is a pattern you’ll use again and again—the same validation logic, different thresholds per environment.

The key insight is that you’re separating concerns. The validation logic (checking length, format, blocked keywords) stays in shared utilities. The configuration (what minimum length means in dev vs. production) lives in environment-specific JSON files. This keeps your code DRY and makes it obvious at a glance what changes between environments.

// hooks/commit-message.mjs




// Load environment-specific config
function loadConfig() {
  const env = process.env.CLAUDE_ENV || "development";
  const configDir = path.join(process.cwd(), ".claude", "hook-configs");

  // Load base config
  const baseConfig = JSON.parse(
    fs.readFileSync(path.join(configDir, "base.json"), "utf8"),
  );

  // Load environment-specific overrides
  const envConfig = JSON.parse(
    fs.readFileSync(path.join(configDir, `${env}.json`), "utf8"),
  );

  // Merge: environment config overrides base config
  return { ...baseConfig, ...envConfig };
}

export async function hook(toolInput) {
  const { commitMessage } = toolInput;
  const config = loadConfig();
  const errors = [];

  // Check minimum length
  if (config.minLength && commitMessage.length < config.minLength) {
    errors.push(
      `Commit message too short (${commitMessage.length}/${config.minLength} chars)`,
    );
  }

  // Check maximum length
  if (config.maxLength && commitMessage.length > config.maxLength) {
    errors.push(
      `Commit message too long (${commitMessage.length}/${config.maxLength} chars)`,
    );
  }

  // Check conventional commits format (if required)
  if (config.requireConventionalCommits) {
    const conventionalPattern =
      /^(feat|fix|docs|style|refactor|test|chore)(\(.+\))?!?: .+/;
    if (!conventionalPattern.test(commitMessage)) {
      errors.push(
        `Must follow conventional commits format (feat/fix/docs/etc): ${commitMessage}`,
      );
    }
  }

  // Check for issue references (if required)
  if (config.requireIssueReference) {
    const issuePattern = /#\d+/;
    if (!issuePattern.test(commitMessage)) {
      errors.push(`Must reference an issue (#123) in the commit message`);
    }
  }

  // Check against blocked keywords
  if (config.blockedKeywords) {
    for (const keyword of config.blockedKeywords) {
      if (commitMessage.toLowerCase().includes(keyword.toLowerCase())) {
        errors.push(`Blocked keyword found: "${keyword}"`);
      }
    }
  }

  if (errors.length > 0) {
    return {
      allow: false,
      reason: errors.join("\n"),
    };
  }

  return { allow: true };
}

Now we need the configuration files. These go in .claude/hook-configs/.

Base configuration (applies to all environments by default):

{
  "minLength": 10,
  "maxLength": 100,
  "requireConventionalCommits": false,
  "requireIssueReference": false,
  "blockedKeywords": ["HACK", "TODO", "FIXME"]
}

Development configuration (relaxed for fast iteration):

{
  "minLength": 5,
  "maxLength": 200,
  "requireConventionalCommits": false,
  "requireIssueReference": false,
  "blockedKeywords": []
}

Production configuration (strict for safety):

{
  "minLength": 20,
  "maxLength": 72,
  "requireConventionalCommits": true,
  "requireIssueReference": true,
  "blockedKeywords": ["HACK", "TODO", "FIXME", "WIP", "DEBUG"]
}

Staging configuration (moderately strict):

{
  "minLength": 15,
  "maxLength": 80,
  "requireConventionalCommits": true,
  "requireIssueReference": false,
  "blockedKeywords": ["HACK", "WIP", "DEBUG"]
}

Here’s how it behaves:

# Development environment
export CLAUDE_ENV=development
git commit -m "fix stuff"  # ✅ Passes (5 chars, no requirements)

# Staging environment
export CLAUDE_ENV=staging
git commit -m "fix stuff"  # ❌ Fails: too short, missing format

# Production environment
export CLAUDE_ENV=production
git commit -m "fix stuff"  # ❌ Fails: too short, missing format, missing issue ref
git commit -m "fix: update parser (#4521)"  # ✅ Passes

This is elegant because the hook code doesn’t change. You’re just loading different configuration based on environment. When you need to adjust strictness, you update a JSON file, not code. When you add a new environment, you create a new config file. Scaling is effortless.

Using Environment Detection Beyond Config Loading

Config files are great, but sometimes you need runtime logic that changes based on environment. You might want to skip certain checks entirely in dev, or call external validation services only in production. This is where you integrate environment detection into your hook logic directly:

// hooks/code-quality.mjs



export async function hook(toolInput) {
  const { changedFiles } = toolInput;
  const env = process.env.CLAUDE_ENV || "development";
  const errors = [];

  // Always lint—but different rules
  const lintResult = execSync("npm run lint", { encoding: "utf8" });
  if (lintResult.includes("error")) {
    errors.push(`Linting failed`);
  }

  // Only run expensive tests in staging/production
  if (env !== "development") {
    const testResult = execSync("npm test -- --coverage", {
      encoding: "utf8",
    });
    if (!testResult.includes("PASS")) {
      errors.push(`Tests failed`);
    }
  }

  // Only check security scanners in production
  if (env === "production") {
    const scanResult = execSync("npm audit", { encoding: "utf8" });
    if (scanResult.includes("high")) {
      errors.push(`High-severity vulnerabilities found`);
    }
  }

  if (errors.length > 0) {
    return {
      allow: false,
      reason: errors.join("\n"),
    };
  }

  return { allow: true };
}

In this hook, development skips expensive tests and security scans entirely (for fast iteration), staging/production run security checks, and production runs full test coverage. Same hook, three different behaviors. This is more efficient than maintaining three separate hooks.

Real-World Complications and How to Handle Them

Before we dive deeper, let’s talk about the complications that show up in real teams. One common issue is inconsistent environment naming. Team member A names their environment “dev”. Team member B uses “development”. CI/CD uses “prod” but some services use “production”. Before long, your hooks are checking for a dozen different environment names and failing silently when they don’t match.

Another complication is environment drift. A developer sets up their local environment once and never updates it. They’re running with an old version of the config file. They don’t realize staging changed its requirements three months ago. They make assumptions about what their local environment allows, then get surprised when they deploy to staging and suddenly hooks fail.

The solution is making environment detection explicit and loud. If your system can’t determine the environment, fail with a clear error message rather than silently defaulting to development. If the config file doesn’t exist, log why and what’s missing. When a developer is confused about their environment, they should be able to run a command and get immediate, clear output: “You’re in development environment with config X loaded, which enforces Y, Z, and Q rules.”

Sharing Base Logic Across Environments

The pattern we’re using—base config plus environment overrides—scales beautifully. You can extract common logic into utility functions and let each environment specialize. This approach keeps your code maintainable as complexity grows.

// hooks/utils/validation.mjs

export function validateCommitFormat(message, pattern) {
  return pattern.test(message);
}

export function validateLength(value, min, max) {
  if (min && value.length < min) {
    return { valid: false, reason: `Too short (${value.length}/${min})` };
  }
  if (max && value.length > max) {
    return { valid: false, reason: `Too long (${value.length}/${max})` };
  }
  return { valid: true };
}

export function checkBlockedContent(text, blockedItems) {
  for (const item of blockedItems) {
    if (text.includes(item)) {
      return { valid: false, reason: `Blocked: ${item}` };
    }
  }
  return { valid: true };
}

Then your environment-specific hooks become thin wrappers:

// hooks/commit-message.mjs


  validateCommitFormat,
  validateLength,
  checkBlockedContent,
} from "./utils/validation.mjs";


export async function hook(toolInput) {
  const { commitMessage } = toolInput;
  const config = loadConfig();
  const errors = [];

  // Use shared validation utilities
  const lengthCheck = validateLength(
    commitMessage,
    config.minLength,
    config.maxLength,
  );
  if (!lengthCheck.valid) errors.push(lengthCheck.reason);

  if (config.requireConventionalCommits) {
    const pattern = /^(feat|fix|docs|style|refactor|test|chore)(\(.+\))?!?: .+/;
    if (!validateCommitFormat(commitMessage, pattern)) {
      errors.push("Must follow conventional commits");
    }
  }

  const blockedCheck = checkBlockedContent(
    commitMessage,
    config.blockedKeywords || [],
  );
  if (!blockedCheck.valid) errors.push(blockedCheck.reason);

  if (errors.length > 0) {
    return { allow: false, reason: errors.join("\n") };
  }

  return { allow: true };
}

This approach keeps your code DRY. The validation logic lives in one place, but the config and requirements change per environment. When you need to add a new validation rule, you update the utility once. When you need different strictness per environment, you update the config files.

Detecting Environment from Git Metadata

Sometimes you don’t want to rely on environment variables. Maybe you’re running Claude Code in an environment where you can’t easily set variables, or you want automatic detection without manual configuration. You can inspect Git configuration and remotes:

// hooks/utils/detect-environment.mjs




export function detectEnvironment() {
  // Check explicit env var first
  if (process.env.CLAUDE_ENV) {
    return process.env.CLAUDE_ENV;
  }

  // Check git remote URL
  try {
    const remoteUrl = execSync("git config --get remote.origin.url", {
      encoding: "utf8",
    }).trim();

    // Example: if remote is on production server
    if (remoteUrl.includes("production")) return "production";
    if (remoteUrl.includes("staging")) return "staging";
  } catch {
    // Not a git repo or no remote
  }

  // Check git branch
  try {
    const branch = execSync("git rev-parse --abbrev-ref HEAD", {
      encoding: "utf8",
    }).trim();

    // Convention: production/main, staging/develop
    if (branch === "main" || branch === "master") return "production";
    if (branch === "develop" || branch === "staging") return "staging";
  } catch {
    // Not a git repo
  }

  // Default to development
  return "development";
}

Then use it in your hooks:



export async function hook(toolInput) {
  const env = detectEnvironment();
  console.error(`[hook] Detected environment: ${env}`);

  // Use detected environment to load config
  // ...rest of hook logic
}

This is useful when you need “magic” environment detection, but be aware: it’s slightly slower (shell calls) and depends on Git conventions. Explicit environment variables are cleaner in CI/CD contexts where you control the execution environment.

Logging and Debugging Environment-Specific Behavior

You want to know which config was loaded when a hook runs. Add logging so you can trace decisions:

// hooks/commit-message.mjs

function loadConfig() {
  const env = process.env.CLAUDE_ENV || "development";
  const configDir = path.join(process.cwd(), ".claude", "hook-configs");

  console.error(`[hook:commit-message] Loading config for environment: ${env}`);

  const baseConfig = JSON.parse(
    fs.readFileSync(path.join(configDir, "base.json"), "utf8"),
  );
  console.error(`[hook:commit-message] Loaded base config`);

  const envConfigPath = path.join(configDir, `${env}.json`);
  if (!fs.existsSync(envConfigPath)) {
    console.error(
      `[hook:commit-message] Environment config not found: ${envConfigPath}`,
    );
    return baseConfig;
  }

  const envConfig = JSON.parse(fs.readFileSync(envConfigPath, "utf8"));
  console.error(
    `[hook:commit-message] Loaded environment config (${env}), overrides:`,
    Object.keys(envConfig),
  );

  return { ...baseConfig, ...envConfig };
}

Claude Code hooks write their console.error output to the hook log, so you can trace which config was loaded. When a developer reports “the hook is being too strict,” you can check the logs and see exactly what environment and config were active.

Progressive Strictness Pattern

A pattern that works really well: develop is permissive, staging adds most requirements, production is locked down. This progression matches how teams actually operate. Code goes through stages of increasing strictness, matching the risk profile of each environment:

// .claude/hook-configs/development.json
{
  "blockedKeywords": [],
  "requireConventionalCommits": false,
  "requireTests": false,
  "requireSecurityScan": false
}

// .claude/hook-configs/staging.json
{
  "blockedKeywords": ["HACK", "WIP"],
  "requireConventionalCommits": true,
  "requireTests": true,
  "requireSecurityScan": false
}

// .claude/hook-configs/production.json
{
  "blockedKeywords": ["HACK", "WIP", "DEBUG", "TODO"],
  "requireConventionalCommits": true,
  "requireTests": true,
  "requireSecurityScan": true
}

This matches how teams actually operate: “let me experiment in dev, get review-ready in staging, lock it down in production.” Each environment has appropriate guardrails without being overly restrictive.

Troubleshooting Common Environment Configuration Issues

Even with the best setup, things go wrong. Here are the patterns that catch teams off guard:

Environment variable inheritance: A developer sets CLAUDE_ENV in their shell, but when they open a new terminal window, it’s not set. They run a hook and get unexpected behavior. The fix is documenting where environment variables should be set (in .zshrc, .bashrc, .env files) and having hooks detect and log what they found.

Config file version skew: The production config file gets updated, but a developer’s local copy is stale. They test locally with outdated rules, it works, they deploy, production fails. The solution is making config files versioned (include a version field) and having hooks warn if they detect version mismatches.

Environment detection false positives: You detect environment by branch name. Your developer creates a local branch called production-hotfix. The hooks think they’re in production. They commit something they shouldn’t. The solution is explicit environment specification: never rely on heuristics alone, always allow explicit override via environment variable.

Config file parsing errors: A team member edits the config JSON, introduces a syntax error, and suddenly all hooks fail silently. The hook has permission issues reading the config directory. A process doesn’t have the right environment variables set. The solution is comprehensive error logging that explains exactly what went wrong and how to fix it.

Key Takeaways

Environment-specific hooks aren’t just about strictness—they’re about matching governance to context. Your development team needs speed; your production systems need certainty. The same validation logic can serve both, you just need smart config loading and clear separation of concerns.

Use environment variables for clarity and control. Share utility logic to stay DRY. Log what config you loaded so debugging is painless when something goes wrong. Once you have this pattern working, extending it to other hooks (push validation, CI checks, branch protection rules) becomes straightforward. Each hook can have its own configuration strategy, or you can build a meta-framework where all hooks use the same loading pattern. Either way, you’re separating logic from configuration, making the system flexible without making it complicated.

Your future self debugging hooks at 2 AM will be grateful you put this infrastructure in place now. You’ll quickly look at the config that was active. You’ll understand the rules. You’ll see what failed and why. You won’t be lost in conditionals scattered through code. Environment-specific configs transform hooks from one-size-fits-all controls into intelligent governance that adapts to context. You’re not fighting against your hooks; you’re working with them.

—iNet

Free Discovery Call

Start With a Conversation, Not a Commitment

Every engagement begins with a free 30-minute discovery call. We'll map what's slowing your business down and tell you exactly what we'd fix first – no pitch deck, no obligation.