Changing API endpoint between development and production (React/Django)

2k Views Asked by At

I am developing a react app inside of a django project and connect them using the Django rest framework. For making API calls from within the react app I am using axios.

Now in my development environment, I obviously call a localhost URL to access the API. For this, I have a file that contains an axios instance:

import axios from "axios";

export const axiosInstance = axios.create({
  baseURL: "http://127.0.0.1:8000/api/",
  timeout: 60000,
});

Obviously, my API calls don't work in production as the URL differs from the one above. I am compiling my react app to a static file which I include in my django project so I don't think I could really add any code that checks for the environment.

One idea that I had is that I could include a file into my project that I would not push into production and then check for whether this file exists or not and adjust the url in an if statement. However, I am not sure if that is a good solution or how I would implement this in plain Javascript.

I am happy to hear any thoughts on this

Edit

After thinking about my question, it actually doesn't make any sense - I am compiling my file before committing it so it can't be dynamic anyways. What I actually need is one main.js file which I am using in development and another one that I would use in production. However, I have no idea how I could achieve this as I am not bundling any files in production? Maybe there is a way of always bundling two files - one with the localhost url and the other one with my production url.

I am using the django-webpack-loader application which tells my django application which file to load into the html file. By accessing environment variables, I could arrange that change. But how do I tell webpack to make the two distinct bundles?

2

There are 2 best solutions below

0
On
// separate js file
baseURL = ""
FirstEndpoint = `${baseURL}/addition/`
...etc

change the baseURL in production.

2
On

I think you could use something like dotenv to access environment variables to configure your baseURL.

This question asks if it is possible, and there are many solutions discussed there, like using .env and configuring it with webpack at build time, mind that with the last one you'll require dotenv-webpack plugin.