Setting up environment variables for React Ionic Capacitor app

Hello everyone, in this tutorial we are going to learn how can we use environment variable in React-Capacitor mobile app.

If you want to set up react-capacitor application, please refer to this article :


Let's walkthrough the App.js code, which only consists of a button ,clicking on that button app calls an endpoint.


import React from 'react';
import axios from 'axios';
const App = () =>{
  const getData = () =>{
    console.log("Current environment : ",process.env.NODE_ENV)
    axios.post(`${process.env.PUBLIC_URL}/getdata`)
    .then(response => console.log(response))
    .catch(err => console.log(err))
  }
  return (
    <div>
      <button onClick={getData} >Get Data</button>
    </div>
  );
}
export default App;

In this example, process.env.VAR_NAME is being used. But when react code will be compiled to native code base this settings will not work, as process.env will be not recognised.

So we need to copy end variables in a separate file. Here for this example we will create a separate folder "env" within 'src' folder.


In this example we will consider two environments "dev" and "prod". You can create more(like: stage,qa etc) as per your requirement."env.dev.js" will hold all env variables in "dev" environment.
"env.prod.js" will hold all values for prod environment.

env.dev.js


export const ENV = {
    ENDPOINT : "https://dev.sample-endpoint.com",
    CURRENT_ENV : "dev"
}


env.prod.js


export const ENV = {
    ENDPOINT : "https://prod.sample-endpoint.com",
    CURRENT_ENV : "prod"
}


Now we will write a script to copy these files content to env.js file as per environment selected by user. Based on that we will also add custom build script in package.json as well.

script.js


const fs = require('fs')
function copyEnvFileSync(){
    let env = process.env.NODE_ENV
    if(!process.env.NODE_ENV){
        env = "dev"
    }
    const fileData = fs.readFileSync(`src/env/env.${env.trim()}.js`,'utf-8')
    fs.writeFileSync('src/env/env.js',fileData,'utf-8');
    console.log('Environment file copied successfully')
}
copyEnvFileSync();


Now, in package.json we will add a custom build script called "cap-build" :


"scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "cap-build":"set NODE_ENV=dev && node ./src/env/script.js && npm run build"
  },

We now have all the setup for using environment variables in capacitor app , so lets update App.js file  based on these above changes:

Updated App.js


import React from 'react';
import axios from 'axios';
import { ENV } from './env/env'
const App = () =>{
  const getData = () =>{
    console.log("Current environment : ",ENV.CURRENT_ENV)
    axios.post(`${ENV.ENDPOINT}/getdata`)
    .then(response => console.log(response))
    .catch(err => console.log(err))
  }
  return (
    <div>
      <button onClick={getData} >Get Data</button>
    </div>
  );
}

export default App;

Now if we run "npm run cap-build" it will work perfectly.

Thanks for your time. :)

Comments

Popular posts from this blog

Best coding practice and structure for redux saga with react hooks | Separate watcher and worker saga | React clean code

How to use redux with React Hooks - Creating TodoList

Setting up Redux Devtools for React applications