Access YAML environment variables in React application
P粉320361201
2023-08-30 20:02:17
<p>I am developing a React application which will be deployed in 3 environments.
Development/QA and Product. </p>
<p>The Devops team provided me with a YAML file containing environment variables and asked us to use these variables in our application. </p>
<p>Example YAML -</p>
<pre class="brush:php;toolbar:false;">---
apiVersion: apps/v1
labels:
app: kubesphere
component: ui-dev
tier: frontend
name: ui-dev
namespace: Test Project
spec:
matchLabels:
app: kubesphere
component: ui-dev
tier: frontend
template:
metadata:
labels:
app: kubesphere
component: ui-dev
tier: frontend
spec:
containers:
-env:
- name: BACKEND_URL
value: http://192.40.84.98:5656
image: $REGISTRY/$HARBOR_NAMESPACE/$APP_NAME:$IMAGE_VERSION-$BUILD_NUMBER
imagePullPolicy: Always</pre>
<p>The variable we must access is BACKEND_URL. </p>
<p>I'm using them in our app as - process.env.BACKEND_URL but it doesn't work. </p>
<p>Did I miss anything? Please guide. </p>
You cannot access
process.env
from client side JavaScript (browser) in which case it is react. Therefore, even if the container has that environment variable, JavaScript cannot access it.The way React uses env variables is that React reads them from the
.env
file, and then in the build React takes those variables and persists them as JavaScript code.In your case the image (react app) is already built so it can't Access those environment variables in the container..