How to make API calls to different environments?

Hello everyone, I am developing a small website using vanilla HTML, CSS, JS. In my JS files a make a couple of api calls using the Fetch API, but I need to change the base path when I am running locally (from time to time I need to call a local instance of the backend), test or prod environment. I did not find a good way to handle this situation, is there anything I can do? Also, I'll need to put the whole thing in an Nginx container and serve it from docker, is there any way I can deploy the same image in every environment? Or am I tied to having an image for every environment for the sake of changing the base URL?
6 Replies
TheNoviceTrader
TheNoviceTrader11mo ago
What have you tried so far? And are you using docker with kubernetes?
Essay
Essay11mo ago
I am using docker compose not kube, but I did not try anything because I really don’t know how to start. On the backend I usually handle this type of things with env variables, but I don’t know how to make it work in the browser
TheNoviceTrader
TheNoviceTrader11mo ago
How about this for an idea 💡 When running docker-compose up you use --env-file ./config/.env.dev Or --env-file ./config/.env.test Or --env-file ./config/.env.prod This sets it to run on a different port (82, 81, 80 or 8442, 8441, 443) JavaScript then sets the API urls based on the port. This should keep it to one code base.
Essay
Essay11mo ago
Correct me if I’m wrong, this approach sets different env variables for each environment, but I cannot do that for js that runs in the browser, I cannot simply do process.env.BASE_URL. This has to be resolved on the server before the js file is sent to the client. The only way that comes to my mind to do so is creating my own server (e.g. with Express) to do that specific bit of SSR, but I was wondering if there is a standard way to solve this problem by only using nginx and static files
Joao
Joao11mo ago
There is, but it involves doing something similar to what you described which is reading environment variables and injecting a small script tag at the head of the html document. Take a look at this for details: https://www.freecodecamp.org/news/how-to-implement-runtime-environment-variables-with-create-react-app-docker-and-nginx-7f9d42a91d70/ The example here talks about React but don't mind that, it applies to any front-end web application including vanilla JS.
Essay
Essay11mo ago
Thanks, this is what I was looking for 🙂