<p>For my React App made with <code>create-react-app</code>, I want to use Kubernetes secrets as environment variables.</p>
<p>These secrets are used for different NodeJS containers in my cluster and they work just fine. I used a shell to echo the variables within the frontend container itself, and they are there but I realize that the environment variables are not loaded in the React App.</p>
<p>I have ensured that the environment variable keys start with <code>REACT_APP_</code>, so that is not the problem.</p>
<p>Here are some files:</p>
<p><code>frontend.yml</code></p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: frontend
  labels:
    app: frontend
spec:
  selector:
    matchLabels:
      app: frontend
  replicas: 1
  template:
    metadata:
      labels:
        app: frontend
    spec:
      containers:
      - name: frontend
        image: build_link
        ports:
        - containerPort: 3000
        envFrom:
          - secretRef:
              name: prod
</code></pre>
<p>Dockerfile</p>
<pre><code>FROM node:17.0.1-alpine3.12

RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app

# latest yarn
RUN npm i -g --force yarn serve

COPY package.json yarn.lock .

RUN yarn --frozen-lockfile

# Legacy docker settings cos node 17 breaks build
ENV NODE_OPTIONS=--openssl-legacy-provider

COPY . .

RUN yarn build

ENV NODE_ENV=production

EXPOSE 3000

CMD [&quot;yarn&quot;, &quot;prod&quot;]

</code></pre>
<p>Kubernetes <code>prod</code> secret</p>
<pre><code>kubectl describe secret prod
Name:         prod
Namespace:    default
Labels:       &lt;none&gt;
Annotations:  &lt;none&gt;

Type:  Opaque

Data
====
REACT_APP_DOCS_SERVER_URL:      41 bytes
REACT_APP_AUTH0_CLIENT_ID:      32 bytes
REACT_APP_AUTH0_DOMAIN:         24 bytes
</code></pre>
<p>env of react app console logged in production (sorry i was desperate)</p>
<pre class="lang-yaml prettyprint-override"><code>FAST_REFRESH: true
NODE_ENV: &quot;production&quot;
PUBLIC_URL: &quot;&quot;
WDS_SOCKET_HOST: undefined
WDS_SOCKET_PATH: undefined
WDS_SOCKET_PORT: undefined
</code></pre>

<p>The build command for <code>create-react-app</code> takes in environment variables present during the build phase, causing the environment variables added later to be missing.</p>
<p>The fix I made involves combining removing the build command in the Dockerfile and then combining the build and run command in the same command:
<code>package.json</code></p>
<pre class="lang-json prettyprint-override"><code>{
  ...
  &quot;scripts&quot;: {
    &quot;prod&quot;: &quot;yarn build &amp;&amp; serve build -l 3000&quot;,
    &quot;build&quot;: &quot;react-scripts build&quot;
  }
}
</code></pre>
