How can I change Environments variables in Electron between production and stage

Viewed 6511

I want to change API URL depending on the environments. for example

production: https://example.com
stage: https://stage.example.com
local: https://localhost:3001

In Electron, How can I set Environment variables?

I tried to change production name when I build but it was useless

2 Answers

Actually, after packaging your app we can't pass the env variable.

I mean even if we try to define or add process env variable. It will be useless in production. I'd say process.env.NODE_ENV will be undefined on production mode. Recommend to use electron-is-dev to check if the app is in development mode or production mode.

package.json

"production": "electron-builder .",
"stage": "cross-env NODE_ENV=stage electron .",
"local": "cross-env NODE_ENV=development electron ."

at you main.js or index.js

const isDev = require('electron-is-dev');

let apiURL = 'https://localhost:3001';

if (isDev) { // or if(process.env.NODE_ENV)
    // Dev or Stage
    if(process.env.NODE_ENV === 'stage')
         apiURL = "https://example.com";
} else {
    // Prod mode
    apiURL = "https://example.com";
    console.log('Running in production');
}

With node you can use process.env.

In your code:

if(process.env.NODE_ENV === 'production') {
 // use production api
 const api = 'https://example.com';
}

or use a switch case:

switch (process.env.NODE_ENV) {
 case 'production':
  // use production api
  const api = 'https://example.com';
  break;
 case 'stage':
  // use stage api
  const api = 'https://stage.example.com';
  break;
 case 'local':
  // use local api
  const api = 'https://localhost:3001';
  break;
 default:
  // use a default this api
}

And in your terminal when using Electron:

$ NODE_ENV=production electron index.js

Or add it as script in your Package.json

"production": "NODE_ENV=production electron index.js",
"stage": "NODE_ENV=stage electron index.js",
"local": "NODE_ENV=local electron index.js"

Then you can use it:

$ npm run production
$ npm run stage
$ npm run local
Related