Shafayet
Shafayet

Reputation: 173

React Application Environment Variable Undefined after Deploying

enter image description here

The Application is Deployed via Gitlab Kubernetes. After its deployed the env is undefined

enter image description here

Just want to know how do i use env in React like Next.js

Upvotes: 2

Views: 322

Answers (1)

Harsh Manvar
Harsh Manvar

Reputation: 30180

You can use the React-dotenv : https://www.npmjs.com/package/react-dotenv

Example code :

import React from "react";
import env from "react-dotenv";

export function MyComponent() {
  return <div>{env.MY_VARIBLE}</div>;
}

deployment.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: test
spec:
  replicas: 1
  selector:
    matchLabels:
      component: test
  template:
    metadata:
      labels:
        component: test
    spec:
      imagePullSecrets:
        - name: test-image
      containers:
        - name: test
          image:test/image:v12
          ports:
            - containerPort: 80
          env:
          - name: MY_VARIBLE
            value: "hello world"

Option 2

Use config.json to store environment variables

config.json

{
  DATA: "$DATA",
  URL: "$URL"
}

code example

import { Component } from '@angular/core';
import Config from "../config.json";

@Component({
  selector: 'app-root',
  templateUrl: './app.hello.html'
})
export class AppComponent {
  environment = Config.DATA;
  baseUrl = Config.URL;
}

Read more at : https://developers.redhat.com/blog/2021/03/04/making-environment-variables-accessible-in-front-end-containers#inject_the_environment_variables

Upvotes: 1

Related Questions