0

Currently in my electron project I have a file .env In it I have:

SHOPIFY_STORE=example.com
SHOPIFY_API_KEY=<key>
SHOPIFY_API_SECRET=<secret key>

In my project I try to access these with process.env In example:

console.log(process.env.SHOPIFY_STORE)

This logs as undefined. When I

console.log(process.env)

I get

NODE_ENV
: 
"development"
PUBLIC_URL
: 
""
WDS_SOCKET_HOST
: 
undefined
WDS_SOCKET_PATH
: 
undefined
WDS_SOCKET_PORT
: 
undefined

It appears my env is being ignored. Is there anything I need to set to get it to be usable?

FabricioG
  • 3,107
  • 6
  • 35
  • 74

1 Answers1

1

METHOD 1:

In your mian file where you create browser window instance, require "path", and "dotenv" (also initialize dotenv), trigger ipcMain event handles inter-process communication (IPC) between the main process and renderer processes.

Finally, add a property called preload option inside webPreferences which looks like this:

import {
  BrowserWindow,
  ipcMain,
} from "electron";

const path = require("path");
const config = require("dotenv");
config.config();

ipcMain.on("invokeEnv", (event) => {
   event.sender.send("envReply", config);
});

let win = new BrowserWindow {
width: 500,
height: 600,
webPreferences: {
  nodeIntegration: true,
  contextIsolation: false,
  preload: path.join(__dirname, "preload.js"),
 },
};

You can create preload.js file inside app folder, inside preload.js paste below block of code.

const electron = require("electron");

async function getConfig() {
let config = null;
  const ipcRenderer = electron.ipcRenderer || false;
  if (ipcRenderer) {
    ipcRenderer.on("envReply", (event, arg) => {
      config = arg.parsed;
      return config.parsed;
    });
    ipcRenderer.send("invokeEnv");
  }
}

getConfig();

A preload.js script exposes the module that the renderer needs.

Hence, you do not have to require ipcRenderer (or any other node module) in your renderer js file, you can use it directly and it should work now

Now you will be able to console.log(process.env.SHOPIFY_STORE) in your js file or any component in case you are using React/Next.js

I would like to tell you one thing:

In preload.js

The dotenv config object will return an object with another object inside it called "parsed".

And inside "parsed" object you will get all ENV's defined in .env file

Please do not get confused by the above explanation, all environments can still be obtained by calling process.env.YOUR_ENV_NAME

METHOD 2:

const config = require("dotenv");
config.config();

Just require and initialize the dotenv module in your main file e.g where you create browser window

Note: Method 2 has been tested on Nextron only✅

Nextron => Electron.js + Next.js For more info Nextron

METHOD 3:

A portable ENV access method

Some References:

Saleheen Noor
  • 261
  • 2
  • 8