Keep a URL in an ENV variable
Two reasons to keep a URL in an ENV variable
I. Supporting different environments
One of the biggest reasons to have environment variables in the first place is ... supporting different configurations for different environments, mostly non-production and production.
Let's imagine that your app integrates with a payment system. You would like to test if the integration works. In theory, you can use the production. You would pay with the "real money". Why not? It's possible.
But what if the integration doesn't work? What if the payment provider accepted your money, but you misimplemented the rest of the flow? And what if you would like to test the payment rejection? What about retesting it after each change?
A lot of ifs.
The better approach is to have a non-production environment that integrates with a non-production payment provider environment.
A non-production allows you to test the payment flow without using "real money". After the tests, you should have a guarantee that the integration works. Even in production. Because, for the production environment, only the payment provider URL will change. The code stays the same.
II. A URL may change
A URL that points to the production usually does not change. However, the non-production URL is an entirely different story. Testing environments are often treated without respect. Their resources are bent, moved around, or deleted. It's better to prepare for a change and have environment variables in place. Especially if the URL does not use a hostname but an IP.
How to set URLs in ENV variables
Once I joined a project where I found the following environment variable.
BEAGLE_API_URL=https://www.dogs.com/breed/beagle
And I started thinking to myself. The author heard that URLs should be configured in environment variables, but nobody explained why.
What is wrong with the current implementation?
Imagine that the application is about to be extended. The new feature relies on a different dog breed, e.g., a Labrador.
Following the current structure, the app requires the following addition.
LABRADOR_API_URL=https://www.dogs.com/breed/labrador
You see the problem? Each integration with a new path requires a new environment variable. And what if the hostname of the URL changes? Then, for each of the environment variables, an adjustment is required.
BEAGLE_API_URL=https://www.dogs.com/breed/beagle
LABRADOR_API_URL=https://www.dogs.com/breed/labrador
BULLDOG_API_URL=https://www.dogs.com/breed/bulldog
POODLE_API_URL=https://www.dogs.com/breed/poodle
A URL environment variable should only store the hostname (and the protocol) of the URL. The code implementation should have integration with proper paths.
DOGS_API_URL=https://www.dogs.com
This way, a change in the URL hostname requires adjustment in only one place.
DOGS_API_URL=https://www.new-dogs.com