2

I'm developing a full-stack web app, which has both a frontend and a backend. In production, my frontend will be hosted at https://frontend.com, and my backend at https://backend.com. It seems reasonable to hardcode the address https://backend.com in my frontend code.

However, when I am testing the app locally, I'll want to spin up the backend at, say, localhost:8000, and redirect my frontend to this address instead. My question is: what's the easiest/most elegant way to do this?

One approach is to manually change the frontend code to point to localhost:8000 for local testing, and then change it back before deploying. However, this is quite annoying, and it's too easy to forget to change it back.

An approach I've used in the past is:

  1. Create a file server.js containing:
    const LOCAL_SERVER = "http://localhost:8000"
    
  2. Import this file in my frontend HTML:
    <script src="server.js"></script>
    
  3. Set a fallback to the remote/production server in my JS scripts:
    let SERVER = typeof LOCAL_SERVER === 'undefined' ? 'https://backend.com' : LOCAL_SERVER
    
  4. Add server.js to my .gitignore.

This works, but it feels kind of hacky, and it pollutes my production code with references to this (possibly non-existent) server.js and LOCAL_SERVER constant. I'm wondering if anyone has a better way.

1 Answers1

0

If your real backend & local backend use the same port, a simple solution is to add the following line to your hosts file:

127.0.0.1   backend.com