Environment variables allow you to define different values depending on the environment in which the application is started. These variables are replaced with their values at runtime.
A typical use case is defining URLs for external APIs. For example, development and production environments can use different API URLs.
Quick guide
A typical environment setup can look like this:
./environment/
├── production.json
└── staging.json
In this example staging.json could contain the following variables:
{
"apiUrl": "https://staging.api.mobilitysuite.de",
"rootCategory": "rootCategoryStaging"
}
The environment variables can then be referenced using the $env()$ keyword with the variable name.
{
"type": "request",
"params": {
"url": "$env(apiUrl)$/api/productDetail/productForOption/{{prodId}}",
"method": "GET"
}
}
The variable apiUrl resolves to https://staging.api.mobilitysuite.de in the staging.json environment.
Environment files
./environment directory
Environment files are JSON files stored in the ./environment directory.
./environment/
├── production.json
└── staging.json
Environment file structure
Environment files contain key-value pairs. The keys identify the variables.
The environment production.json could contain the following variables:
{
"apiUrl": "https://api.mobilitysuite.de",
"rootCategory": "rootCategoryProduction"
}
The filename identifies the environment.
Using environment variables
You can reference environment variables using the $env()$ keyword with the variable name.
For example, the following request uses the apiUrl environment variable to define the request URL:
{
"type": "request",
"params": {
"url": "$env(apiUrl)$/api/productDetail/productForOption/{{prodId}}",
"method": "GET"
}
}
In this example, $env(apiUrl)$ is replaced with the value of apiUrl defined in the active environment, i.e. https://staging.api.mobilitysuite.de in the staging.json environment, or https://api.mobilitysuite.de in the production.json environment.
Setting the environment
The active environment can be selected in the mos.launcher when starting local hosting of your app.
Troubleshooting
If an environment variable does not work as expected, check the following:
- Is the environment file stored in the
./environment directory?
- Does the variable name in
$env(variableName)$ match the key in the environment file?
- Is the variable defined in the environment file used by the application?