cant access process.env varibales inside node module - javascript

apply-platform
env-bundle
node_modules
node-client
I have a repo apply-platform that has env variables and node modules, in the node module there is another repo node-client.
When I try to access process.env variables inside node-client project I get following object as process.env
{
\"LANG\":\"en_US.UTF-8\",\"PATH\":\"/home/ubuntu/bin:/home/ubuntu/.local/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games:/snap/bin\",\"HOME\":\"/home/ubuntu\",\"LOGNAME\":\"ubuntu\",\"USER\":\"ubuntu\",\"SHELL\":\"/bin/bash\",\"PM2_USAGE\":\"CLI\",\"PM2_HOME\":\"/home/ubuntu/.pm2\",\"SILENT\":\"true\",\"env_production\":\"[object Object]\",\"instance_var\":\"NODE_APP_INSTANCE\",\"exec_mode\":\"cluster_mode\",\"env\":\"[object Object]\",\"treekill\":\"true\",\"autorestart\":\"true\",\"automation\":\"true\",\"pmx\":\"true\",\"vizion\":\"true\",\"merge_logs\":\"true\",\"cwd\":\"/srv/cbax-apply-platform/\",\"log_type\":\"json\",\"instances\":\"4\",\"name\":\"www\",\"node_args\":\"\",\"pm_exec_path\":\"/srv/cbax-apply-platform/server.js\",\"pm_cwd\":\"/srv/cbax-apply-platform\",\"exec_interpreter\":\"node\",\"pm_out_log_path\":\"/home/ubuntu/.pm2/logs/application.log\",\"pm_err_log_path\":\"/home/ubuntu/.pm2/logs/application.log\",\"pm_pid_path\":\"/home/ubuntu/.pm2/pids/www-13.pid\",\"km_link\":\"false\",\"vizion_running\":\"false\",\"NODE_APP_INSTANCE\":\"0\",\"PM2_JSON_PROCESSING\":\"true\",\"_\":\"/usr/bin/pm2\",\"XDG_DATA_DIRS\":\"/usr/local/share:/usr/share:/var/lib/snapd/desktop\",\"SHLVL\":\"1\",\"PWD\":\"/srv/cbax-apply-platform/\",\"PORT\":\"8080\",\"NODE_ENV\":\"test\",\"REGION\":\"USEastTest\",\"www\":\"{}\",\"status\":\"launching\",\"pm_uptime\":\"1629364026293\",\"axm_actions\":\"\",\"axm_monitor\":\"[object Object]\",\"axm_options\":\"[object Object]\",\"axm_dynamic\":\"[object Object]\",\"created_at\":\"1629364026181\",\"pm_id\":\"13\",\"restart_time\":\"10\",\"unstable_restarts\":\"0\",\"_pm2_version\":\"2.6.1\",\"versioning\":\"null\",\"node_version\":\"9.11.1\",\"exit_code\":\"0\"}
How can I access process.env variables inside the node-module (node-client)
I tried console.log(JSON.stringify(process.env.env)) it still gives me [object][object] as output;
I found this object comes from ecosystem.config.js file of apply-platform , so added these 2 variables and pushed it to the server, but when I console process.env i cant see these 2 variables in node-client

The Node injects the process.env global variable at runtime in our app to use, and it represents the state of the system environment of our app when it starts. So, for example, if the system has the PATH variable set, this will be accessible to you through the process.env.PATH variable you can use to check where binaries are located and make external calls to them if required.
When we write the code, we can never be sure where our app can be deployed. If we require the database in development, we spin up the instance of it, and we link to it via a connection string , something like 127.0.0.1:3306. However, when deploying it to the server in production, we might need to link it to the remote server, 32.22.2.1.
Accessing environment variables in Node.js is supported out of the box. When your Node.js process boots up, it will automatically provide access to all the existing environment variables by creating the env object as a property of the process global object.
Explicitly loading variables from the .env file.
npm install dotenv --save
Afterward, add the following line to the very top of your entry file (index.js or app.js).
require('dotenv').config();

There is a npm module that loads environment variables from .env files into process.env, called dotenv. In your case, you would use it like this:
const dotenv = require("dotenv")
dotenv.config({ path: "/path/to/.env/"})
You could then access the environment variables in Node.js like this:
process.env.MYVAR
If you don't want the variables specified in the .env file to mangle with other environment variables, you can also do this:
const buffer = Buffer.from("PORT=3000") //example
const env = dotenv.parse(buffer) // returns object -> { PORT: 3000 }
// env.PORT would return 3000
dotenv.parse accepts a buffer object and returns an object, instead of binding it to process.env. You could also use the fs module to read the contents of the .env file, and pass it to dotenv.parse.
To learn more, reference the npm page for dotenv: https://www.npmjs.com/package/dotenv

Related

When is `.env` defined variables are used on Next.js Applications?

When using Next.js to create web application, we can use environment variable files like .env.development and .env.production. And fill it with env variables like below;
NEXT_PUBLIC_API_ENDPOINT="https://some.api.url/api"
And my question is "When are these variables used?"
When I build next.js application with next build, it prompts:
> next build
info - Loaded env from ~/project/folder/.env.production
info - Loaded env from ~/project/folder/.env
And When I serve build result with next start :
> next start
ready - started server on 0.0.0.0:3000, url: http://localhost:3000
info - Loaded env from ~/project/folder/.env.production
info - Loaded env from ~/project/folder/.env
So this means env is loaded on build-time, and run-time.
But there must be one time where ENV variables are loaded and used.
When is these variables defined in the env file are used?
Because there may be access to these variables both at build-time AND at runtime.
For example:
Your build will use them to create built outputs, like static code
At runtime your code may require in-process access to them, like for handling server-side requests

Unable to access process variable in Vue3JS Vite project

I am creating a vue3 application (created with Vite) that interacts with a smart contract written in Solidity and stored on Ropsten. Therefore I am using web3js to interact with my smart contracts and also web3.storage in order to store some images on IPFS. I have a .env file at the root of my project storing my API key for web3.storage :
VUE_APP_API_TOKEN=VALUE
VITE_API_TOKEN=VALUE
The problem is that apparently web3.storage expects the API token to be stored in process.env and I am unable to access the global process variable from my application. I am always getting an error Uncaught ReferenceError: process is not defined.
I think, this is linked to my usage of Vite instead of pure Vue3.
I tried to export process env in the vite.config.ts file with that code but it didn't work:
export default ({ mode }) => {
process.env = { ...process.env, ...loadEnv(mode, process.cwd(), '') };
console.log(process.env.VITE_API_TOKEN) //Works fine: VALUE is logged
console.log(process.env.VUE_APP_API_TOKEN) //Works fine: VALUE is logged
return defineConfig({
plugins: [vue()]
});
}
How could I access the process variable from my vue files in order to get the values of my environment variable and make web3.storage work?
.env
VITE_WEB3_STORAGE_TOKEN="your_token"
SomeComponent.vue: (or any other file of your app, really):
console.log(import.meta.env.VITE_WEB3_STORAGE_TOKEN) // "your_token"
Note: as specified in vite documentation, only variables prefixed with VITE_ will be exposed:
To prevent accidentally leaking env variables to the client, only variables prefixed with VITE_ are exposed to your Vite-processed code.
If you're running the build script in CI you will need to make sure that you're creating / populating the relevant .env file before you run the build script.

How can I create environment variables and use them in a react library, without using webpack?

I have tried dotenv and cros-env. And also with mentioning it in this link
https://create-react-app.dev/docs/adding-custom-environment-variables/
However, it doesn't work for me
My .env file
MY_VAR=value
I have this in the file where I want to call it
console.log(process.env)
const { MY_VAR } = process.env
console.log(MY_VAR)
and i get this
As noted here, environment variables for your frontend must begin with REACT_APP. So try REACT_APP_MY_VAR and restart your React server afterwards.

How to set a dynamic env var in node.js

I want to add a dynamic env var in my node.js app, in other words i wanted the env value to be determined through a function. so i can't add it manually in my .env file.
I'am using webpack as a module bundler and i want to access that env var in my webpack.config file.
Assuming you're running the node server on a linux machine. You need to export all your environment variables manually or via a script like so: export PORT=3000;, then accesses them directly via the node process object like so:
const port = process.env.PORT || 5000;.
Or you could install a dependency like config (https://www.npmjs.com/package/config) and have it manage pulling your environment variables into the code for use.

How do I load a node module as if the current module were located somewhere else?

I have some nodejs code running in a module somewhere. From this module, I would like to load a module located in a completely different place in the file system -- for example, given the path "/another/dir" and the module name "foo", I would like Node to act as if a module running in /another/dir had called require("foo"), rather than my own module.
My code is running here
/some/folder/node_modules/mine/my_module.js
I have the path "/another/dir/", the string "foo",
and want to load this module
/another/dir/node_modules/foo/index.js
In other words, the module documentation refers to the process "require(X) from module at path Y", and I would like to specify my own value for Y
Can this be accomplished? If so, how? If not, why not?
The simplest, is just to resolve the path into an absolute path, this will be the recommended approach for most if not all cases.
var path = require('path');
var basedir = '/another/dir';
var filename = 'foo'; // renamed from dirname
var filepath = path.join(basedir, 'node_modules', filename);
var imports = require(filepath);
If you really need to make require act as if it is in a different directory,
you can push the base directory to module.paths
module.paths.unshift('/another/dir/node_modules');
var imports = require('foo');
module.paths.shift();
module.paths can also be modified externally via the environment variable NODE_PATH, tho that would be the least recommended approach but this does apply it globally across all modules.
A symlink with npm link
To avoid problems or modify source code I would use npm link, from your example:
First:
cd /another/dir/node_modules/foo # go into the package directory
npm link # creates global link
This will create a global link for the foo module, on Linux you need root permissions to do this.
Then:
cd /some/folder/ # go into some other package directory.
npm link foo # link-install the package
/some/folder/package.json should contain foo as a dep, is not mandatory, without it you get an extraneous warning with npm ls:
"dependencies": {
[...]
"foo": "*"
}
No symlink with local NODE_PATH
You don't like symlinks ? You can still use NODE_PATH but locally instead setting a global variable as #rocketspacer suggested, because as he rightly stated, it's not recommended to use it globally.
Note: In any case I would use a User variable and not a System-wide variable, a co-worker could log with a different username on the same machine and still get a modified NODE_PATH.
But to do this locally for just one invocation on Linux you can simply call:
NODE_PATH=$NODE_PATH:/another/dir/node_modules npm start
It will use that NODE_PATH only for that invocation.
Same one time invocation on Windows:
#ECHO OFF
SET BASE_NODE_PATH=%NODE_PATH%
SET NODE_PATH=%BASE_NODE_PATH%;C:\another\dir\node_modules\
node index.js
SET NODE_PATH=%BASE_NODE_PATH%
And...
You could also use a local dep like:
"dependencies": {
"foo": "file:/another/dir/node_modules/foo"
}
But would require an npm install and it would copy the content of foo in the current package node_modules folder.
It's quite easy to achieve, just add absolute paths to module object
in your current script /some/folder/node_modules/mine/my_module.js add this
module.paths.push('/another/dir/node_modules');
//this must be absolute, like /Users/John/another/dir/node_modules
var foo = require('foo');
For demo, open node in terminal, and type module.paths, it will show all the path node will search for require, you just add your path
"require(X) from module at path Y"
Means calling require(X) from within a file located at path Y. So you practically can't change Y.
Although the above solutions work (modifying module.paths & requiring absolute path), you'll have to add those snippets to every file in your project where you need requiring the foreign modules.
Even more, modifying module.paths is not officially supported. So it's not guaranteed to work in future updates of node
Introducing NODE_PATH
NODE_PATH is an environment variable that is set to a colon-delimited list of absolute paths.
Within those absolute paths, Node.js will search for a module that matches your require statement when all else has failed (Having indexed node_modules up to File System Root and still no match was found)
It is officially supported, although not recommended as it goes against convention (Your co-worker may not be aware of the NODE_PATH usage as there is no descriptive way of telling that in your project itself)
Notes:
On Windows, NODE_PATH is delimited by semicolons instead of
colons.
Node doesn't look for node_modules within those paths like
its default behavior, so your paths should be exactly where you
contain needed modules. For example: "/another/dir/node_modules"
Detailed information can be found on NodeJs official document:
https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders
For those of you who are unaware of what environment variables is and how to set them, I have a windows screenshot that will get you started
In simple lines, u can call your own folder as module :
For that we need: global and app-module-path module
here "App-module-path" is the module ,it enables you to add additional directories to the Node.js module search path And "global" is, anything that you attach to this object will b available everywhere in your app.
Now take a look at this snippet:
global.appBasePath = __dirname;
require('app-module-path').addPath(appBasePath);
__dirname is current running directory of node.You can give your own path here to search the path for module.

Categories