6

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

Mikinovation
  • 107
  • 1
  • 1
  • 8

2 Answers2

5

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');
}
tpikachu
  • 4,478
  • 2
  • 17
  • 42
2

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
  • 1
    hmm...I want to change the variables after distribute. when I download electron app, I can't change it – Mikinovation Jun 03 '20 at 05:59
  • Once your app is packed you need to change it manually in the source code. U can add a global api route and define this one in your app so you can just change the url in your api. – Gert-Jan Wille Jun 03 '20 at 07:47
  • 2
    I don't want to change manually. When I push to github. The CI will be triggered and electron-builder will run. After that, It will be automatically uploaded on AWS S3 and Each users application will be autoupdated. So when should I change it? – Mikinovation Jun 03 '20 at 08:37