ENV
The ENV submodule provides a centralized way to access Environment Variables within a Salesforce Org. It decouples configurations, URLs, endpoints, and environment-specific toggles from hardcoded Apex code using Custom Metadata Types.
Documentation
💾 Source Code
Implementation
- The
ENVclass provides key-value retrieval operations - The
Environment_Variable__mdtis a Custom Metadata Type where key-value pairs are stored. DeveloperName matches the key, and the custom fieldValue__cstores the value - To minimize query usage and optimize run-time execution,
ENVqueries all metadata records on first load usingEnvironment_Variable__mdt.getAll(). The values are cached in a static, in-memory map throughout the Apex transaction EnvironmentVariableis an inner domain class representing a single environment variable with two properties:key(String): The developer name of the variable.value(String): The custom setting or metadata value stored.
Demos
apex
// Retrieve environment variable by DeveloperName
Env.EnvironmentVariable configVar = Env.get('My_Custom_Endpoint');
if (configVar != null) {
String endpointUrl = configVar.value;
System.debug('Target Endpoint: ' + endpointUrl);
} else {
System.debug('Environment variable not found.');
}Benefits
- Leverages platform-native caching of Custom Metadata (
getAll()) to ensure retrieving configurations consumes zero SOQL queries - Allows changing configuration keys (such as API keys, environment tags, or feature toggles) declaratively in Sandbox or Production settings without redeploying Apex
- Provides a clean domain model (
EnvironmentVariable) rather than passing raw SObjects or metadata records directly in logic layers
