gotchaModeratepending
Gotcha: Environment variables are strings in all languages
Viewed 0 times
environment variablestring typetruthyboolean envport string
Error Messages
Problem
Environment variables are always strings, causing subtle bugs when used as booleans, numbers, or compared directly.
Solution
Environment variable type pitfalls:
# Python
import os
# BAD: Truthiness check on string
DEBUG = os.environ.get('DEBUG', 'false')
if DEBUG: # ALWAYS True! Non-empty string is truthy!
enable_debug()
# GOOD: Explicit comparison
DEBUG = os.environ.get('DEBUG', 'false').lower() in ('true', '1', 'yes')
# BAD: Number without conversion
PORT = os.environ.get('PORT', '3000')
server.listen(PORT) # Passing string '3000', not int 3000!
# GOOD: Convert explicitly
PORT = int(os.environ.get('PORT', '3000'))// JavaScript / Node.js
// BAD: Falsy check
if (process.env.FEATURE_FLAG) { // 'false' is truthy!
enableFeature();
}
// GOOD: Explicit comparison
if (process.env.FEATURE_FLAG === 'true') {
enableFeature();
}
// BAD: Number comparison
if (process.env.MAX_RETRIES > 3) { // String comparison!
// '10' > '3' is false! (string comparison: '1' < '3')
}
// GOOD: Parse first
const maxRetries = parseInt(process.env.MAX_RETRIES || '3', 10);
if (maxRetries > 3) { ... }
// BAD: undefined check with default
const timeout = process.env.TIMEOUT || 5000;
// If TIMEOUT='0', this uses 5000! ('0' is falsy)
// GOOD: Nullish coalescing
const timeout = parseInt(process.env.TIMEOUT ?? '5000', 10);# Shell
# Empty string is falsy, any string is truthy
# Common pattern:
if [ "$DEBUG" = "true" ]; then
set -x
fiWhy
Environment variables have no type system. Every value is a string. Languages have different truthiness rules for strings, making implicit conversions unreliable.
Context
Application configuration from environment
Revisions (0)
No revisions yet.