6

In webpack.config file declared a variable to read in application.

let BASEURL = "http://127.0.0.1:8090";

with this approach I am not able to update BASEURL after npm run build. Every time I want to generate a new build for each environment if BASEURL changes.

Is there any way to build once and deploy build file in multiple environments with minimal changes?

2
  • Think that you should do it in your index.js or whatever file which is a part of your code base that is being build and there you can do whatever check you want with process.env.ENV_VARIABLE.
    – sehrob
    Commented Apr 4, 2018 at 12:24
  • I need solution after build. So the same build can be used in multiple env's
    – Chandu
    Commented Apr 4, 2018 at 13:10

1 Answer 1

11

Tl;dr: use AJAX and have the config either in react context or in a global variable.


Detailed answer:

It is indeed as you state, after the application is built with npm run build, the environment variables become hardwired and cannot be changed.

The official statement of create-react-app is it does not support the build once deploy many principle. From https://create-react-app.dev/docs/adding-custom-environment-variables/ :

The environment variables are embedded during the build time. Since Create React App produces a static HTML/CSS/JS bundle, it can’t possibly read them at runtime.

However, there are ways of achieving the principle, just a bit more complicated. The idea is, you need to get the value of a variable at runtime from an external source, e.g. AJAX. In more details, possible solutions may be (but are not limited to) following:

1. server-side placeholder replacement

This is a solution proposed by create-react-app in https://create-react-app.dev/docs/title-and-meta-tags/#injecting-data-from-the-server-into-the-page, introducing a custom placeholder and replacing it with the data on the server, before it is rendered to clients.

<!doctype html>
<html lang="en">
  <head>
    <script>
      window.SERVER_DATA = __SERVER_DATA__;
    </script>

While this works, it introduces a major overhead, because it leaves the whole backend implementation up to you. Depending on your tech stack, this may be very easy or also very complicated to implement.

2. a dynamic <script> that assigns variable values

A solution proposed in https://www.cotyhamilton.com/build-once-deploy-anywhere-for-react-applications/ utilizes the dynamic nature of javascript. In the dynamically downloaded config.js file, a value is assigned to the variable. In the rest of the React code, the variable is read and used. You can change the config.js file any time, without the need of recompiling the react app.

// public/config.js

const apiUrl = 'localhost:1337';
const env = 'development';
<!-- public/index.html -->

<script src="%PUBLIC_URL%/config.js"></script>
<script>
  window.config = { apiUrl, env };
</script>

The main downside is that this does not support TypeScript, and your IDE or linter may complain that apiUrl and env are not defined. Especially in bigger projects, this approach may be hard to maintain.

3. dynamic config with AJAX, with TypeScript support

Based on the 2nd solution, this article https://profinit.eu/en/blog/build-once-deploy-many-in-react-dynamic-configuration-properties/ describes in a great detail how to best achieve the build once deploy many principle with create-react-app and what are pros and cons.

It proposes downloading the dynamic config as a JSON with AJAX. The main caveat is to make sure that the dynamic config is downloaded BEFORE some code tires to use it. In the context of React lifecycle, there are two ways of how to achieve this.

3.1 global variable

Download the dynamic config JSON from globalConfigUrl, store it in a global variable, and only then render the React app. Example in TypeScript:

// index.tsx:
import axios from "axios";
import React, {ReactElement} from "react";
import App from "./App";
import {globalConfig, globalConfigUrl} from "./configuration/config";

axios.get(globalConfigUrl)
  .then((response) => {
    globalConfig.config = response.data; // THIS IS THE IMPORTANT LINE
    return <App />;
  })
  .catch(e => {
      return <p style={{color: "red", textAlign: "center"}}>Error while fetching global config</p>;
  })
  .then((reactElement: ReactElement) => {
    ReactDOM.render(
      reactElement,
      document.getElementById("root")
    );
  });

Full working example: https://codesandbox.io/s/build-once-deploy-many-global-config-object-dvpzr

3.2. React context

Wrap your <App> component with a react context provider containing the configuration (with undefined or some default value). Fetch the configuration first time App is rendered and then save its value to the context. React will take care of the rest and will propagate the value change!

Full working example: https://codesandbox.io/s/build-once-deploy-many-react-context-7lk7g

The basic idea is this. Check the article above / working example for all details:

// App.tsx
import {useConfig} from "./configuration/useConfig";

// ... in the method: 
  const { setConfig } = useConfig(); // the `useConfig` is a custom hook, wrapping a React context. See the full working example for all details
  useEffect(() => {
    axios
      .get(dynamicConfigUrl)
      .then((response) => {
        setConfig(response.data);
      })
  }, [setConfig]);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.