How to run both frontend and backend on the same URL. (Not really, but you’ll get the idea.)

You might already know this or think that I am dumb for saying this, but the fact is I didn’t know this was possible until I was in a bit of a pickle.

What happened was that I needed to show images in my frontend that were secure, and I wanted to inject those images via innerHTML as well. So let me explain how I solved that.

I found out that most API responses will not contain a base URL. We were not storing the base URLs in the database but were applying the base URLs to the image URLs via environment variables in the backend, but for the <img/> tags to load them, I didn’t need the base URLs, so I removed them.

Then the <img/> tags were trying to load the images from the frontend URL, localhost:4200, but the secure images were stored in AWS which can be accessed by calling a secured endpoint in my backend.

My pickle was to change the <img/> tags’ base URL with port 4200 to 5000, seems simple, right ? But I don’t know how to do that, so I did what all of us do…

I ChatGPTed how to run both my frontend and backend on the same port. I know the simple version sounds dumb, but I was creative in my prompting and explained my situation. ChatGPT replied that you cannot run both frontend and backend on the same port, but what you can do is set up a proxy.conf.json file inside your Angular project to port forward your API calls to the backend.

This is the proxy.conf.json file I was given:

{
    "/api": {
    "target": "http://localhost:5000",
    "secure": false,
    "changeOrigin": true
    }
}

These seven lines of code saved me a lot of time and effort.

Now every call to localhost:4200/api will be forwarded to localhost:5000

If you’ve spent the time to read this in full, you’ll see that I mentioned the images I was showing in my frontend were secured. So, can you guess how I used the <img/> tag to show secured images? That will be in my next one. It’s no big deal, all the big players use this method. I just didn’t know it, that’s all….