how to set and get environment variable in node js? - javascript

I am trying to set and get environment variable in node js .I tried like this
I create the test.js file
And add this line
console.log(process.env.NODE_ENV);
Run like this
set NODE_ENV=production&&node test.js
It gives me undefined

NODE_ENV=production node test.js on linux and $env:NODE_ENV = 'production'; node test.js in powershell.

In addition to the accepted answer:
From nodejs docs
It is possible to modify this object, but such modifications will not be reflected outside the Node.js process.
So you can also do something like:
process.env.foo = 'bar';
console.log(process.env.foo);
Assigning a property on process.env will implicitly convert the value to a string.
process.env.test = null;
console.log(process.env.test);
// => 'null'
Note: There are some env variables which you can set only before any codes are executed.
Also note:
On Windows operating systems, environment variables are case-insensitive.
process.env.TEST = 1;
console.log(process.env.test);
// => 1

1. create a package.json file.
2. install the dotenv npm package
make a .env file in your root directory.
//env
NODE_ENV=development
PORT=8626
# Set your database/API connection information here
API_KEY=**************************
API_URL=**************************
Now if you want to call your port in any file or server.js it will be like this.
const port = process.env.PORT;
console.log(`Your port is ${port}`);

Related

next.js environment variables are undefined (Next.js 10.0.5)

I am coding a website with Next.js and I tried to add google Tag Manager.
I followed the tutorial on the Next.js Github example but for some reasons I can't access to my environment variables.
It says my variable is undefined.
I created a file .env.local on my project folder (at the same level as components, node_modules, pages, etc)
In this file I created a variable like this (test purpose) :
NEXT_PUBLIC_DB_HOST=localhost
And on my index page I tried this code :
console.log("test ", process.env.NEXT_PUBLIC_DB_HOST);
But in my console I get a "test undefined".
I tried to put my variable into an .env file instead, without success.
What I am doing wrong ?
This envs just works in Server Side. To access this envs in Client Side, you need declare in the next.config.js
This way:
module.exports = {
reactStrictMode: true,
env: {
BASE_URL: process.env.BASE_URL,
}
}
Create .env (all environments), .env.development (development environment), and .env.production (production environment).
Add the prefix NEXT_PUBLIC to all of your environment variables.
NEXT_PUBLIC_API_URL=http://localhost:3000/
Use with prefix process.env
process.env.NEXT_PUBLIC_API_URL
Stop the server and restart it:
npm run dev
I hope it works.
This solution for latest version of nextJs (above 9)
Restarting the server worked for me.
Edit & save .env.local
Stop the server and restart it, npm run dev
You should get an output on the next line like this:
> klout#0.1.0 dev
> next dev
Loaded env from [path]/.env.local
For those using NextJS +9 and looking for environment variables in the browser, you should use the NEXT_PUBLIC_ prefix. Example:
NEXT_PUBLIC_ANALYTICS_ID=123456789
See documentation for reference.
After spending countless hours on this, I found that there is a tiny little paragraph in both the pre and post nextjs 9.4 documentation:
(Pre-9.4) https://nextjs.org/docs/api-reference/next.config.js/environment-variables (same as this answer)
Next.js will replace process.env.customKey with 'my-value' at build time.
(^9.4) https://nextjs.org/docs/basic-features/environment-variables
In order to keep server-only secrets safe, Next.js replaces process.env.* with the correct values at build time.
Key words being BUILD TIME. This means you must have set these variables when running next build and not (just) at next start to be available for the client side to access these variables.
This is my next.config.js file.
/** #type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
env: {
BASE_URL: process.env.NEXT_PUBLIC_SITE_URL,
},
};
module.exports = nextConfig;
Restart the server and it worked fine. using Nextjs 12.1.0 with typescript
In my case, Im pasting REACT_APP_API_URL instead of NEXT_PUBLIC_API_URL.
Adding with the most recent version of the documentation on this, v12+.
Using the next.config.js file you can specify server and client variables:
module.exports = {
serverRuntimeConfig: {
// Will only be available on the server side
mySecret: 'secret',
secondSecret: process.env.SECOND_SECRET, // Pass through env variables
},
publicRuntimeConfig: {
// Will be available on both server and client
staticFolder: '/static',
},
}
You can still use an env.local file, and pass the variable in to the next.config.js file. For example:
publicRuntimeConfig: {
DB_URL: process.env.DB_URL
}
And then you can access the variable like this:
import getConfig from 'next/config';
const { publicRuntimeConfig } = getConfig();
publicRuntimeConfig.DB_URL;

How to use an environment variable value in another environment variable name and value using dotenv?

For my testing framework I'm using dotenv to read and initialize environment variables for different test environments. Now I want to use a specific environment variable value as a part of the value and the name of another environment variables.
So, I set the env var export INSTANCE=1 before initializing the env file with dotenv.
This is my env file with all the env vars I want to initialize with dotenv:
# INSTANCE as part of env var value
MY_DOMAIN="http://mypage/"$INSTANCE""
# INSTANCE as part of env var name
SUBDOMAIN"$INSTANCE"="/mysubdomain"
And this metric is also not working:
# INSTANCE as part of env var value
MY_DOMAIN=http://mypage/${INSTANCE}
# INSTANCE as part of env var name
SUBDOMAIN${INSTANCE}=/mysubdomain
This is possible doing it via bash with
export MY_DOMAIN="http://mypage/"$INSTANCE"" SUBDOMAIN"$INSTANCE"="/mysubdomain"
echo $MY_DOMAIN
http://mypage/1
echo $SUBDOMAIN1
/mysubdomain
But using dotenv it is not working for me. I have the following code:
const dotenv = require("dotenv");
var result = dotenv.config({ path: '/path/to/my/env/file' });
console.log(result.parsed);
The console.log produces the following result:
{
MY_DOMAIN:'http://mypage/"$INSTANCE"'
}
So, the env var INSTANCE can not be used, the value will be ignored. Are there any solution to solve my issue?
I have found a solution using dotenv-expand :)

NodeJS environment variables undefined

I'm trying to create some envrioment variables but when I create the file and run the server the seem to be undefined. I'm using nodemon. I have restarted my server and no luck.
UPDATED
.env
MONGO_ATLAS_PW = "xxxx";
JWT_KEY = "secret_this_should_be_longer";
package.json
...
"scripts": {
...
"start:server": "nodemon ./server/server.js"
}
app.js
require('dotenv').config();
...
console.log(process.env.JWT_KEY); //undefined
I believe the nodemon.json file is only for setting nodemon specific configuration. If you look at the nodemon docs for a sample nodemon.json file, the only env variable they mention setting is NODE_ENV.
Have you considered putting these environment variables for your app in a .env file instead? There is a package called dotenv that is helpful for managing env variables in Node.
First, install dotenv using the command npm install dotenv
Then, create a file called .env in the root directory with the following:
MONGO_ATLAS_PW=xxxxx
JWT_KEY=secret_this_should_be_longer
Finally, inside your app.js file after your imports add the following line:
require('dotenv').config()
I believe you're referring to the dotenv package. To configure it, first create a file called .env with your keys and values stored like so:
MONGO_ATLAS_PW=xxxxx
JWT_KEY=secret_this_should_be_longer
Then, in your server.js, add this near the top:
require("dotenv").config();
Then the process.env variable will be an object containing the values in .env.
This needed to be in the root directory of my project.
nodemon.json
{
"env": {
"MONGO_ATLAS_PW": "xxxx",
"JWT_KEY": "secret_this_should_be_longer"
}
}
The env variable do not contain the trailing white spaces and also remove the quotes
MONGO_ATLAS_PW = "xxxx";
JWT_KEY = "secret_this_should_be_longer";
to
MONGO_ATLAS_PW=xxxx
JWT_KEY=secret_this_should_be_longer
and restart the server
or you can also try using the nodemon.json - create a new file called nodemon.json in your root directory
{
"env": {
"MONGO_ATLAS_PW" : "xxxx",
"JWT_KEY" : "secret_this_should_be_longer"
}
}
and restart the server
for accessing the variable
process.env.MONGO_ATLAS_PW
process.env.JWT_KEY

how do I make webpack not convert process.env variables to their values during build?

I have the following in one of my project files:
const baas = process.env.DBID;
console.log('baas', baas);
If I run:
cross-env PORT=4000 NODE_ENV=production WEBPACK_CONFIG=browser_prod,server_prod webpack --colors
My server.js file looks like:
const baas = undefined;
console.log('baas', baas);
As expected. However, I want to be able to set the ID when I run the built app not when I build the app, ie:
DBID=someotherid node dist/server.js
So I need webpack to not convert const baas = process.env.DBID to it's value at build time, but rather leave it as is, so the server.js uses it's value at runtime.
How do I do this?
Note: if I manually edit the built server.js and change undefined to process.env.DBID then the run script works and the app uses the env var from run time, but I don't want to edit files after building.
You are using the wrong target.
By default, webpack builds the application to be run in the browser. This means it will mock native node functions like path fs and process
Your target is node, so there is no need to mock these.
Add this to your webpack.config.js
module.exports = {
target: 'node'
};
https://webpack.js.org/concepts/targets/#usage
What you need is process.argv not process.env:
// server.js
const baas = process.argv[0];
console.log('baas', baas);
Then:
node dist/server.js baas_value
For convenience, you can use this module https://www.npmjs.com/package/yargs
I was able to prevent Webpack from converting process.env by accessing it indirectly like this:
const processText = "process";
const _process = global[processText];
app.listen(_process.env.PORT || 2000);
You need to get process indirectly instead of env because the process variable is defined by webpack to be something like /* provided dependency */ var process = __webpack_require__(/*! process/browser */ "process/browser");

How to use in node properties for deployment and local usage

I've created node application which I can run locally and in the cloud
Now I want that it be done somehow smoother and cleaner ,so I try to put some property in config.json file to check if I want to deploy the app or use it locally but I need to update manually this property before I change the propose , there is a better way to do it with node ?
let runnerServer = `http://localhost:8060/service/runner/${server.address().port}`;
if (cfg.isHosted) {
blogServer = `http://${serverName}/service/runner/${server.address().port}`;
}
and in the conig.json I've the field isHosted which I change manually(true/false) if I want to deploy or not...
update
maybe I can use process.env.PORT but this is just one example that I need to use in my code , currently I've several of fork that need to konw if Im in deployment or running locally ..
One option is to use use node's in built object called process.env (https://nodejs.org/api/process.html) and use two config files per se. This approach is somewhat similar to what you are doing but may be cleaner
config.localhost.json
config.production.json
then by setting properties on this object based on environment such as process.env.NODE_ENV = 'localhost' or process.env.NODE_ENV = 'production', you could read the corresponding file to import the configurations.
var config = require('./config.production.json');
if(process.env.NODE_ENV === 'localhost')
{
config = require('./config.localhost.json');
}
So to set this environment variable when running locally on your dev box , if
OSX - then on terminal export NODE_ENV=localhost
WINDOWS - then on cmd line set NODE_ENV=localhost
An easy way to solve this, if every environment configuration can be in the repo:
config.json:
production: {
// prod config
},
staging: {
// staging config
},
devel: {
// devel config
}
config.js:
const environment = process.env['ENV'] || 'devel';
module.exports = require('./config.json')[environment];
then in your package.json you could add the following scripts:
package.json
// npm stuff
scripts {
prod: "ENV=production node index.js",
stage: "ENV=staging node index.js",
dev: "ENV=devel node index.js"
}
and with this setup, you can run each configuration with the following commands:
production: npm run prod
staging: npm run stage
devel: npm run dev

Categories