Photo by Sammyayot254 on Unsplash
How we enabled the backend team to use their local server on the frontend app deployed on a remote server?
Let's say backend is deployed in test-backend.testserver.com and frontend in test-frontend.testserver.com. It works fine but now let's say there's a bug that's getting hard to identify and debugging requires both frontend and backend to work together; simultaneously. The frontend is running on a frontend developer's machine and the backend on a backend developer's own machine. So, either you've got to connect to the same network and use the local IP to test, or use some tunneling services like ngrok to work together.
But what if the frontend application is working fine and it's the backend team that requires UI to test the system. It's often hard using postman or playgrounds or swagger or any other API testing applications, especially if those involve file transfer which was specifically our major concern. When it's the backend team that requires a working frontend, the solution is either to clone the frontend repo and run the code in their own machine redirecting the frontends API requests to their own local server by manipulating the frontend code or involve a frontend developer and get them to connect to a local network. Though it's tiresome, it's often preferable to run the code on their own machine.
We've come to this situation very often. Since frontend applications would have predefined API routes to request to, it's difficult for backend developers to test the deployed frontend using their local server. This was getting hectic. So we came up with an idea. Instead of hardcoding the API URL, instead, we checked if a key, say url, exists on localstorage and if it does, redirect all the API requests to its value.
// get url string from localstorage or from ".env" file
const url = localStorage.getItem('url') ?? import.meta.env.VITE_API_URL;
// get the data from the url
axios.get(url)
However, you need to have CORS enabled to access the local server. Also, if you are hosting the frontend app on "HTTP", you get a CORS error something like this:
Access to XMLHttpRequest at 'localhost:8004/query' from origin 'http://009.00.001.06:8004' has been blocked by CORS policy: The request client is not a secure context and the resource is in more-private address space
local
.
On a quick search, I found that its related to Private Network Access and I couldn't yet find a fix. But once I deployed the frontend app on "HTTPS", the backend team could easily redirect the API request to their local server simply by adding a "url" value on localstorage.