Skip to main content

Environment Manager

Flexible and typed environment manager for JavaScript/TypeScript applications, with support for custom environments and state persistence.

🚀 Basic Usage​

import { createEnvironmentManager } from '@codeleap/debug'

// Define your environments
const environments = {
development: 'http://localhost:3000/',
staging: 'https://staging.myapp.com/',
production: 'https://api.myapp.com/',
custom: '', // customizable environment
} as const

// Configure the manager
const envManager = createEnvironmentManager({
environments,
defaultEnvironment: 'development',
customEnvironment: 'custom',
persistKey: 'my-app-environment', // optional
})

// Enable the manager (required before use)
envManager.setEnabled('user')

// Change environment
envManager.setEnvironment('production')

// Get current server URL
const apiUrl = envManager.serverUrl
console.log(apiUrl) // 'https://api.myapp.com/'

📖 API Reference​

Creation​

createEnvironmentManager<T>(config)​

Creates a new environment manager instance.

Parameters:

  • config.environments: Object with environments and their URLs
  • config.defaultEnvironment: Default environment (key from environments object)
  • config.customEnvironment: Key for the customizable environment
  • config.persistKey: Key for persistence (optional, default: 'environment-manager')

Returns: EnvironmentManager<T>

Properties​

environments​

Returns the object with all configured environments.

const envs = envManager.environments
// { development: 'http://localhost:3000/', ... }

editors​

Constant with available editor types.

envManager.editors.USER    // 'user'
envManager.editors.SYSTEM // 'system'

defaultConfig​

Returns the manager's default configuration.

const config = envManager.defaultConfig
// { environment: 'development', customUrl: '', enabledBy: null }

env​

Returns the current environment state. If not enabled, returns the default config.

const currentEnv = envManager.env
// { environment: 'production', customUrl: '', enabledBy: 'user' }

isEnabled​

Checks if the manager is enabled.

if (envManager.isEnabled) {
// manager is active
}

isEnabledBy​

Returns who enabled the manager ('user', 'system', or null).

const enabledBy = envManager.isEnabledBy // 'user' | 'system' | null

isEnabledByUser​

Checks if it was enabled by the user.

if (envManager.isEnabledByUser) {
// manually enabled
}

isEnabledBySystem​

Checks if it was enabled by the system.

if (envManager.isEnabledBySystem) {
// automatically enabled
}

is​

Object with boolean flags for each environment (with capitalized names).

if (envManager.is.Production) {
console.log('We are in production!')
}

// Check multiple environments
if (envManager.is.Development || envManager.is.Staging) {
console.log('Development environment')
}

serverUrl​

Returns the server URL based on the current environment.

const url = envManager.serverUrl
// 'https://api.myapp.com/' or custom URL

Methods​

setEnabled(by)​

Enables or disables the manager.

Parameters:

  • by: 'user' | 'system' | false

Returns: boolean - true if enabled, false if disabled

envManager.setEnabled('user')     // enable by user
envManager.setEnabled('system') // enable by system
envManager.setEnabled(false) // disable

setEnvironment(environment)​

Sets the current environment. Only works if the manager is enabled.

Parameters:

  • environment: Key of the configured environment
envManager.setEnvironment('production')
envManager.setEnvironment('staging')

isEnvironment(env)​

Checks if the current environment matches the specified one.

Parameters:

  • env: Environment key

Returns: boolean

if (envManager.isEnvironment('production')) {
console.log('We are in production')
}

setCustomUrl(url)​

Sets a custom URL. Automatically adds '/' at the end if necessary and validates the URL.

Parameters:

  • url: Custom URL (must be valid)
envManager.setCustomUrl('https://my-custom-api.com/')
envManager.setEnvironment('custom')

testUrl(url)​

Validates if a URL is in the correct format.

Parameters:

  • url: URL to validate

Returns: boolean

envManager.testUrl('https://api.example.com/')  // true
envManager.testUrl('invalid-url') // false

use()​

React hook to use the manager in components. Returns reactive state.

Returns:

{
enabled: boolean
enabledByUser: boolean
enabledBySystem: boolean
config: { environment: string, customUrl?: string }
changed: boolean
customUrl: string
setCustomUrl: (url: string) => void
}
function MyComponent() {
const env = envManager.use()

return (
<div>
<p>Environment: {env.config.environment}</p>
<p>Enabled: {env.enabled ? 'Yes' : 'No'}</p>
{env.changed && <p>Configuration has changed!</p>}
</div>
)
}

🎯 Examples​

Complete Example​

import { createEnvironmentManager } from '@codeleap/debug'

const environments = {
development: 'http://localhost:3000/',
staging: 'https://staging.myapp.com/',
production: 'https://api.myapp.com/',
custom: '',
} as const

const env = createEnvironmentManager({
environments,
defaultEnvironment: 'dev',
customEnvironment: 'custom',
persistKey: 'myapp-env',
})

// Enable and configure
env.setEnabled('user')
env.setEnvironment('prod')

// Make request
async function fetchData() {
const response = await fetch(`${env.serverUrl}api/users`)
return response.json()
}

// Check environment
if (env.is.Prod) {
console.log('Production mode active')
enableAnalytics()
}

// Custom URL
if (needsCustomEnvironment) {
env.setCustomUrl('https://custom-server.com/')
env.setEnvironment('custom')
}

React Usage​

import { createEnvironmentManager } from '@codeleap/debug'

const envManager = createEnvironmentManager({...})

function EnvironmentSelector() {
const env = envManager.use()

const handleEnable = () => {
envManager.setEnabled('user')
}

const handleEnvironmentChange = (newEnv: string) => {
envManager.setEnvironment(newEnv)
}

return (
<div>
<button onClick={handleEnable}>
{env.enabled ? 'Disable' : 'Enable'}
</button>

{env.enabled && (
<select
value={env.config.environment}
onChange={(e) => handleEnvironmentChange(e.target.value)}
>
<option value="development">Development</option>
<option value="staging">Staging</option>
<option value="production">Production</option>
<option value="custom">Custom</option>
</select>
)}

{env.config.environment === 'custom' && (
<input
type="text"
value={env.customUrl}
onChange={(e) => env.setCustomUrl(e.target.value)}
placeholder="https://custom-api.com/"
/>
)}

<p>Current URL: {envManager.serverUrl}</p>
</div>
)
}

🔒 URL Validation​

The manager automatically validates URLs using the following pattern:

  • Must start with http:// or https://
  • Must end with /
  • Accepts domains, localhost, and IPs
  • Accepts optional ports

Valid URLs:

  • https://api.example.com/
  • http://localhost:3000/
  • http://192.168.1.1:8080/
  • https://sub.domain.example.com:443/

Invalid URLs:

  • http://example.com (no trailing slash)
  • example.com/ (no protocol)
  • ftp://example.com/ (invalid protocol)

💾 Persistence​

The manager's state is automatically persisted using the key configured in persistKey. This means that settings are maintained between page reloads.

const env = createEnvironmentManager({
// ...
persistKey: 'my-unique-key', // State saved in this key
})