npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, πŸ‘‹, I’m Ryan HefnerΒ  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you πŸ™

Β© 2026 – Pkg Stats / Ryan Hefner

git-branch-env

v1.5.0

Published

πŸš€ Automatically load environment variables based on git branch with CI/CD support, encryption, and developer tools

Readme

git-branch-env

πŸš€ Automatically load environment variables based on git branch with CI/CD support, encryption, and developer tools.

npm version License: MIT Node.js CI

✨ Features

  • πŸ”„ Branch-aware environment loading - Automatically loads .env.{branch} files
  • 🏭 CI/CD Integration - Works with GitHub Actions, GitLab CI, CircleCI, Travis, Bitbucket
  • πŸ” Encryption Support - Secure your sensitive environment files with passphrase generation
  • 🎯 Pattern Mapping - Map branch patterns to specific env files (e.g., feature/* β†’ .env.dev)
  • βœ… Validation - Ensure required environment variables are present
  • 🎨 Developer Experience - VSCode integration, git hooks, templates
  • πŸš€ Zero Configuration - Works out of the box with sensible defaults
  • πŸ‘₯ Team Collaboration - Easy sharing and management of environment configurations

πŸš€ Quick Start

# Install globally
npm install -g git-branch-env

# Or use with npx
npx git-branch-env init
npx git-branch-env sync

πŸ“ File Structure

your-project/
β”œβ”€β”€ .env.base                    # Base environment variables (shared)
β”œβ”€β”€ .env.main                    # Production environment
β”œβ”€β”€ .env.dev                     # Development environment
β”œβ”€β”€ .env.staging                 # Staging environment
β”œβ”€β”€ .env.feature-auth            # Feature branch environment
β”œβ”€β”€ .env.feature-auth.example    # Template for feature branch
β”œβ”€β”€ .env.prod.encrypted          # Encrypted production environment
β”œβ”€β”€ branch-env.config.json       # Configuration file
β”œβ”€β”€ .gitignore                   # Excludes .env* files
└── README.md                    # Team documentation

πŸ“‹ File Types Explained

  • .env.base - Shared variables across all environments
  • .env.{branch} - Branch-specific overrides
  • .env.{branch}.example - Templates for new branches
  • .env.{env}.encrypted - Encrypted sensitive files
  • branch-env.config.json - Configuration and mappings

πŸ› οΈ Usage

Basic Usage

// In your application
require('git-branch-env').load();

// Now process.env contains your branch-specific variables
console.log(process.env.DATABASE_URL);

CLI Commands

# Initialize environment file for current branch
npx git-branch-env init

# Load and apply environment variables
npx git-branch-env sync

# Validate environment configuration
npx git-branch-env validate

# Setup git hooks for automatic syncing
npx git-branch-env setup-hooks

# Add .env* to .gitignore
npx git-branch-env gitignore-env

# Export environment variables for shell
npx git-branch-env export

# Add VSCode launch configuration
npx git-branch-env vscode

# Generate secure passphrases
npx git-branch-env generate-passphrase
npx git-branch-env generate-passphrase 32 mixed
npx git-branch-env generate-passphrase 24 alphanumeric
npx git-branch-env generate-passphrase 16 words

# Encrypt/Decrypt environment files
npx git-branch-env encrypt .env.prod "my-secret-passphrase"
npx git-branch-env decrypt .env.prod.encrypted "my-secret-passphrase"

βš™οΈ Configuration

Create branch-env.config.json in your project root:

{
  "mappings": {
    "feature/*": ".env.dev",
    "hotfix/*": ".env.staging",
    "release/*": ".env.staging"
  },
  "requiredKeys": ["DATABASE_URL", "API_KEY"],
  "baseEnv": ".env.base",
  "warnOnTemplate": true,
  "branchSanitizer": {
    "replaceSpecialChars": true,
    "maxLength": 30
  },
  "branchFallbacks": [
    {
      "envVar": "CUSTOM_BRANCH"
    },
    {
      "file": "./branch.txt"
    }
  ]
}

Configuration Options

| Option | Type | Description | |--------|------|-------------| | mappings | Object | Map branch patterns to env files | | requiredKeys | Array | Required environment variables | | baseEnv | String | Base environment file (default: .env.base) | | warnOnTemplate | Boolean | Warn when using template files | | branchSanitizer | Object | Branch name sanitization rules | | branchFallbacks | Array | Fallback methods for branch detection |

πŸ” Encryption & Passphrase Management

git-branch-env provides robust encryption for your sensitive environment files with multiple passphrase options.

πŸ”‘ Passphrase Options

1. Generate Secure Passphrases

# Generate a mixed passphrase (default: 32 chars)
npx git-branch-env generate-passphrase

# Generate specific length and type
npx git-branch-env generate-passphrase 24 alphanumeric
npx git-branch-env generate-passphrase 16 words
npx git-branch-env generate-passphrase 40 symbols

Passphrase Types:

  • mixed - Letters, numbers, and symbols (default)
  • alphanumeric - Letters and numbers only
  • symbols - Letters, numbers, and special characters
  • words - Easy-to-remember word combinations

Examples:

# Mixed (32 chars): w)QoU)emlu9@cAF[S3o=(gw*A]K|eB,L
# Alphanumeric (24 chars): 4XegezfLB7o9WacRLJhg0Koo
# Words (16 chars): eagle-lemon

2. Use Your Own Passphrase

# Use a custom passphrase
npx git-branch-env encrypt .env.prod "my-custom-secure-passphrase-123"

3. Environment Variable Passphrase

# Set passphrase as environment variable
export GIT_BRANCH_ENV_PASSPHRASE="my-secret-passphrase"

# Use in your application
require('git-branch-env').load({ 
  encrypted: true, 
  passphrase: process.env.GIT_BRANCH_ENV_PASSPHRASE 
});

πŸ” Encryption Commands

# Encrypt a file
npx git-branch-env encrypt .env.prod "my-secret-passphrase"

# Decrypt a file
npx git-branch-env decrypt .env.prod.encrypted "my-secret-passphrase"

# Use encrypted file in your app
require('git-branch-env').load({ 
  encrypted: true, 
  passphrase: 'my-secret-passphrase' 
});

πŸ›‘οΈ Security Features

  • AES-256-CBC encryption with random IV
  • HMAC-SHA256 verification for integrity
  • Tamper detection - prevents modification
  • Secure key derivation using SHA-256
  • Environment isolation to prevent leaks

πŸ“‹ Passphrase Best Practices

  1. Length: Use at least 16 characters (32+ recommended)
  2. Complexity: Include letters, numbers, and symbols
  3. Uniqueness: Use different passphrases for different environments
  4. Storage: Store securely (password manager, environment variables)
  5. Rotation: Change passphrases regularly
  6. Backup: Keep secure backups of your passphrases

πŸ”„ Workflow Examples

Scenario 1: Production Environment

# 1. Generate a strong passphrase
npx git-branch-env generate-passphrase 32 mixed
# Output: w)QoU)emlu9@cAF[S3o=(gw*A]K|eB,L

# 2. Encrypt production environment
npx git-branch-env encrypt .env.prod "w)QoU)emlu9@cAF[S3o=(gw*A]K|eB,L"

# 3. Add encrypted file to version control
git add .env.prod.encrypted
git commit -m "Add encrypted production environment"

# 4. Use in your application
require('git-branch-env').load({ 
  encrypted: true, 
  passphrase: process.env.PROD_PASSPHRASE 
});

Scenario 2: Development Team

# 1. Generate easy-to-remember passphrase
npx git-branch-env generate-passphrase 16 words
# Output: eagle-lemon

# 2. Share passphrase securely with team
# (Use password manager, secure chat, etc.)

# 3. Encrypt development environment
npx git-branch-env encrypt .env.dev "eagle-lemon"

# 4. Team members can decrypt when needed
npx git-branch-env decrypt .env.dev.encrypted "eagle-lemon"

Scenario 3: CI/CD Pipeline

# 1. Generate alphanumeric passphrase (no special chars)
npx git-branch-env generate-passphrase 24 alphanumeric
# Output: 4XegezfLB7o9WacRLJhg0Koo

# 2. Set as CI/CD secret
# In GitHub Actions: GIT_BRANCH_ENV_PASSPHRASE

# 3. Use in CI/CD
require('git-branch-env').load({ 
  encrypted: true, 
  passphrase: process.env.GIT_BRANCH_ENV_PASSPHRASE 
});

🚨 Security Warnings

  • ⚠️ Never commit unencrypted .env files
  • ⚠️ Never share passphrases in code or logs
  • ⚠️ Use strong passphrases (avoid common words)
  • ⚠️ Store securely (not in plain text files)
  • ⚠️ Rotate regularly for production environments

🏭 CI/CD Integration

GitHub Actions

name: CI
on: [push]
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: '18'
      - run: npm ci
      - name: Load Environment
        run: npx git-branch-env sync
      - run: npm test

GitLab CI

stages:
  - test
  - build

test:
  stage: test
  script:
    - npm ci
    - npx git-branch-env sync
    - npm test

CircleCI

version: 2.1
jobs:
  test:
    docker:
      - image: cimg/node:18.0
    steps:
      - checkout
      - run: npm ci
      - run: npx git-branch-env sync
      - run: npm test

πŸ‘₯ Team Collaboration

git-branch-env makes it easy for teams to manage environment variables together while maintaining security and consistency.

πŸš€ Initial Team Setup

Step 1: Project Lead Setup

# 1. Initialize the project with git-branch-env
npx git-branch-env init

# 2. Create base environment file
echo "APP_NAME=MyAwesomeApp
APP_VERSION=1.0.0
NODE_ENV=development" > .env.base

# 3. Create development environment
echo "DATABASE_URL=postgres://dev:pass@localhost:5432/dev
API_KEY=dev_key_123
DEBUG=true" > .env.dev

# 4. Create production template (encrypted)
npx git-branch-env generate-passphrase 32 mixed
# Use the generated passphrase to encrypt production env
npx git-branch-env encrypt .env.prod "generated-passphrase"

# 5. Setup git hooks for automatic syncing
npx git-branch-env setup-hooks

# 6. Add to .gitignore
npx git-branch-env gitignore-env

# 7. Commit and push
git add .env.base .env.dev .env.prod.encrypted branch-env.config.json
git commit -m "Setup git-branch-env for team collaboration"
git push origin main

Step 2: Team Member Onboarding

# 1. Clone the repository
git clone https://github.com/yourteam/your-project.git
cd your-project

# 2. Install git-branch-env
npm install --save-dev git-branch-env

# 3. Setup git hooks (optional)
npx git-branch-env setup-hooks

# 4. Get production passphrase from team lead (secure channel)
# 5. Test environment loading
npx git-branch-env sync

πŸ”„ Daily Team Workflows

Scenario 1: Starting a New Feature

# 1. Create feature branch
git checkout -b feature/user-authentication

# 2. Initialize environment for the feature
npx git-branch-env init

# 3. Customize environment if needed
echo "AUTH_SERVICE_URL=http://localhost:3001/auth
JWT_SECRET=feature-jwt-secret" >> .env.feature-user-authentication

# 4. Test your changes
npm test

# 5. Commit and push
git add .env.feature-user-authentication
git commit -m "Add authentication feature environment"
git push origin feature/user-authentication

Scenario 2: Switching Between Branches

# Automatic (with git hooks)
git checkout main
# Environment automatically switches to .env.main

git checkout feature/user-authentication
# Environment automatically switches to .env.feature-user-authentication

# Manual sync if needed
npx git-branch-env sync

Scenario 3: Team Member Joins Existing Feature

# 1. Pull the latest changes
git pull origin feature/user-authentication

# 2. Environment automatically loads
# (git hooks handle this automatically)

# 3. If environment file doesn't exist, use template
# git-branch-env will automatically use .env.feature-user-authentication.example

πŸ” Secure Team Collaboration

Production Environment Management

# Team Lead: Encrypt production environment
npx git-branch-env generate-passphrase 32 mixed
# Share passphrase securely with team (password manager, secure chat)

# Team Members: Use encrypted environment
npx git-branch-env decrypt .env.prod.encrypted "shared-passphrase"
# Or use in application
require('git-branch-env').load({ 
  encrypted: true, 
  passphrase: process.env.PROD_PASSPHRASE 
});

Development Environment Sharing

# Create shared development environment
echo "DATABASE_URL=postgres://dev:pass@dev-db:5432/dev
REDIS_URL=redis://dev-redis:6379
API_BASE_URL=https://dev-api.example.com" > .env.dev

# Commit to repository (safe for development)
git add .env.dev
git commit -m "Update development environment"
git push origin main

πŸ“‹ Team Roles & Responsibilities

Project Lead / DevOps

  • βœ… Setup initial git-branch-env configuration
  • βœ… Manage production passphrases securely
  • βœ… Create and maintain .env.base with shared variables
  • βœ… Setup CI/CD integration
  • βœ… Monitor environment consistency across team

Senior Developers

  • βœ… Create feature branch environments
  • βœ… Review environment changes in pull requests
  • βœ… Maintain environment templates (.env.*.example)
  • βœ… Help team members with environment issues

Team Members

  • βœ… Use npx git-branch-env init for new features
  • βœ… Keep feature environments minimal and focused
  • βœ… Test environment changes locally before committing
  • βœ… Follow team's environment naming conventions

🚨 Team Security Guidelines

What to Commit βœ…

  • .env.base - Shared, non-sensitive variables
  • .env.dev - Development environment (non-sensitive)
  • .env.*.example - Templates for new branches
  • .env.*.encrypted - Encrypted sensitive files
  • branch-env.config.json - Configuration

What NOT to Commit ❌

  • .env.prod - Unencrypted production environment
  • .env.staging - Unencrypted staging environment
  • Any .env files with real API keys, passwords, or secrets
  • Passphrases or encryption keys

Secure Sharing Practices

  • πŸ” Use password managers for passphrases
  • πŸ” Share passphrases via secure channels (not email/Slack)
  • πŸ” Rotate passphrases regularly
  • πŸ” Use different passphrases for different environments
  • πŸ” Limit access to production passphrases

πŸ”„ Pull Request Workflow

When Creating a PR

# 1. Ensure environment files are properly named
ls -la .env*

# 2. Test environment loading
npx git-branch-env validate

# 3. Update documentation if needed
# 4. Create pull request with clear description

When Reviewing a PR

  • βœ… Check that no sensitive data is exposed
  • βœ… Verify environment file naming follows conventions
  • βœ… Ensure .env.*.example files are updated
  • βœ… Test environment loading in the feature branch
  • βœ… Confirm CI/CD tests pass

🎨 Developer Experience

VSCode Integration

npx git-branch-env vscode

This creates a .vscode/launch.json with automatic environment loading.

Git Hooks

npx git-branch-env setup-hooks

Automatically syncs environment when switching branches.

Husky Integration

If you're using Husky, add to .husky/post-checkout:

#!/bin/sh
npx git-branch-env sync

πŸ”§ Advanced Usage

Programmatic API

const gitBranchEnv = require('git-branch-env');

// Load with options
gitBranchEnv.load({
  verbose: true,
  diff: true,
  encrypted: true,
  passphrase: 'secret'
});

// Validate only
gitBranchEnv.validate({ verbose: true });

// Get current branch
const branch = gitBranchEnv.getCurrentBranch();

// Match branch to env file
const envFile = gitBranchEnv.matchBranchToEnv(branch, config);

Environment Variable Expansion

# .env.base
BASE_URL=https://api.example.com
API_VERSION=v1

# .env.dev
API_URL=${BASE_URL}/${API_VERSION}/dev
DEBUG=true

Multiline Values

# .env.prod
PRIVATE_KEY="-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC...
-----END PRIVATE KEY-----"

πŸ§ͺ Testing

# Run all tests
npm run test:all

# Run specific test suites
npm test                    # Unit tests
npm run test:ci            # CI integration tests
npm run test:encryption    # Encryption and passphrase tests

# Test encryption manually
npx git-branch-env encrypt .env.prod my-secret-passphrase
npx git-branch-env decrypt .env.prod.encrypted my-secret-passphrase

πŸ“¦ Installation

# Global installation
npm install -g git-branch-env

# Local installation (recommended for teams)
npm install --save-dev git-branch-env

# Using npx (no installation required)
npx git-branch-env init

πŸ—οΈ Project Setup

# 1. Initialize git-branch-env in your project
npx git-branch-env init

# 2. Setup git hooks for automatic syncing
npx git-branch-env setup-hooks

# 3. Add environment files to .gitignore
npx git-branch-env gitignore-env

# 4. Create your first environment file
npx git-branch-env init --template=typescript

πŸ”§ Troubleshooting

❓ Common Issues & Solutions

Issue: Environment not loading

# Check if git-branch-env is detecting your branch
npx git-branch-env sync --verbose

# Verify your environment file exists
ls -la .env*

# Check branch-env.config.json configuration
cat branch-env.config.json

Issue: Git hooks not working

# Reinstall git hooks
npx git-branch-env setup-hooks

# Check if hooks are executable
ls -la .git/hooks/post-checkout

# Test manual sync
npx git-branch-env sync

Issue: Encryption/Decryption failing

# Verify passphrase is correct
npx git-branch-env decrypt .env.prod.encrypted "your-passphrase"

# Check if encrypted file is corrupted
cat .env.prod.encrypted

# Regenerate passphrase if needed
npx git-branch-env generate-passphrase 32 mixed

Issue: CI/CD not detecting branch

# Check CI environment variables
echo "GITHUB_REF: $GITHUB_REF"
echo "GITLAB_CI: $GITLAB_CI"
echo "CIRCLE_BRANCH: $CIRCLE_BRANCH"

# Use fallback configuration
echo "CUSTOM_BRANCH=main" >> branch-env.config.json

Issue: Validation failing

# Check required keys in configuration
cat branch-env.config.json

# Verify all required variables are set
npx git-branch-env validate --verbose

# Check for missing or empty values
grep -E "^[A-Z_]+=$" .env*

πŸ› Debug Mode

# Enable verbose logging
npx git-branch-env sync --verbose

# Check branch detection
node -e "console.log(require('./index').getCurrentBranch())"

# Test configuration loading
node -e "console.log(JSON.stringify(require('./index').loadConfig(), null, 2))"

πŸ“ž Getting Help

🀝 Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

πŸ§ͺ Development Setup

# Clone the repository
git clone https://github.com/salehammar/git-branch-env.git
cd git-branch-env

# Install dependencies
npm install

# Run tests
npm run test:all

# Run linter
npm run lint

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ™ Acknowledgments

  • Inspired by the need for branch-specific environment management
  • Built with ❀️ for the developer community
  • Thanks to all contributors and users

πŸ“ž Support

πŸ“š Complete Feature Summary

🎯 What git-branch-env Solves

| Problem | Solution | |---------|----------| | Manual environment switching | Automatic branch-based loading | | Environment file management | Pattern mapping and templates | | Sensitive data security | AES-256 encryption with HMAC | | Team collaboration | Shared configurations and secure sharing | | CI/CD integration | Multi-platform support | | Developer experience | Git hooks, VSCode integration |

πŸš€ Key Capabilities

  • βœ… Branch Detection - Works with local git and all major CI platforms
  • βœ… Pattern Mapping - Map branch patterns to specific environments
  • βœ… Template System - Automatic fallback to example files
  • βœ… Encryption - Secure sensitive files with passphrase generation
  • βœ… Validation - Ensure required variables are present
  • βœ… Team Workflows - Complete collaboration guidelines
  • βœ… CI/CD Ready - Works in GitHub Actions, GitLab CI, CircleCI, etc.
  • βœ… Developer Tools - VSCode integration, git hooks, debugging

πŸ“Š Usage Statistics

# Most common commands
npx git-branch-env init          # Initialize environment
npx git-branch-env sync          # Load environment
npx git-branch-env validate      # Validate configuration
npx git-branch-env generate-passphrase  # Generate secure passphrase
npx git-branch-env encrypt       # Encrypt sensitive files

πŸŽ‰ Success Stories

  • Teams: Manage environments across 10+ developers
  • CI/CD: Automated deployments with branch-specific configs
  • Security: Encrypted production environments in version control
  • Productivity: Zero manual environment switching

Made with ❀️ for developers who love clean, automated workflows!

Ready to transform your environment management? πŸš€

# Get started in 30 seconds
npx git-branch-env init
npx git-branch-env setup-hooks
npx git-branch-env sync