How to assign variables in .env file? - javascript

Q1.
I have a .env file in my ReactJS app like this:
API_1_ROOT='http://my-api-1.com'
API_2_ROOT='http://my-api-2.com'
BASE_API=API_1_ROOT // This doesn't work as expected
I want to assign one of these api roots to my base api root; I tried doing this in my .env file but it doesn't work as expected.
How can I do this in my .env file?
Q2.
Also, I am not able to destructure multiple items from process.env like this:
const { API_1_ROOT, API_2_ROOT } = process.env;
When I'm doing this, I'm getting the following error:
Uncaught ReferenceError: process is not defined
I have to do this to get both variables:
const { API_1_ROOT } = process.env;
const { API_2_ROOT } = process.env;

npm install dotenv --save
Next add the following line to your app.
require('dotenv').config()
Then create a .env file at the root directory of your application and add the variables to it.
.env
// contents of .env
REACT_APP_API_1_ROOT = 'my-secret-api-key'
REACT_APP_API_2_ROOT = 'my-secret-api-key'
config.js
require('dotenv').config()
const config = {
api1: process.env.REACT_APP_API_1_ROOT,
api2: process.env.REACT_APP_API_2_ROOT,
}
export default config

Related

Set environment variables outside of pages dir in nextjs?

Is there a way to set env variables outside of a pages directory in NextJS? I have a util function that provides the base API route in one place. However, since this is a util function it's not defined on a page. I'd like to avoid having to create a getStaticProps on every page to get my private env variables if possible.
Any thoughts?
utils/index.ts (not on a nextJS page)
export const apiAddress =
process.env.NEXT_PUBLIC_CURRENT_ENV === 'PRODUCTION'
? process.env.PROD_API
: process.env.DEV_API;
...
I had a similar issue where I couldn't access my env vars in the nextjs application.
The solution was to read them in the next.config.js and pass them implicitly.
My example loads the environment from /environments/env.development but you can use any location you want.
So my next next.config.js looks like this:
const path = require('path')
const { parsed: localEnv } = require('dotenv-safe').config({
allowEmptyValues: false,
path: path.resolve(__dirname, `environments/.env.development`),
})
const nextConfig = {
env: localEnv,
}
module.exports = nextConfig
You should be able to access the ENV vars in your .env file like usually:
process.env.YOUR_VARIABLE
Additionally
Based on environment, you can use a predefined ENV var from your package.json as well which lets you load the right file for your environment.
In your package.json define sth. like that in scriptssection:
"dev:development": "ENV=development node server.js",
"dev:staging": "ENV=staging node server.js"
...
Then you have access to the ENV var and can use it directly for your purposes in next.config.js.
Based on example above:
path: path.resolve(__dirname, `environments/.env.${process.env.ENV}`),

Simple and elegant way to override local file If exists?

Looking for elegant and simple solution to have "local configuration override" files.
The idea is to be able to have local configuration that will not ask to be added to git repository every time.
For that I need to include local.config.js if it exists.
I have global app configuration in config.js with configuration like
export const config = {
API_URL="https://some.host",
}
and config.local.js
export const config = {
API_URL="https://other.address",
}
there's .gitignore:
config.local.js
Difficulty:
I do not want to add a node module to project just for this one thing. I believe there should be an elegant way to do this in one or few lines, but have not found any so far.
Things that I tried:
1.
try {
const {
apiUrl: API_URL,
} = require('./config.local.js');
config. API_URL =apiUrl;
} catch (e) {
}
require does not work inside try{} block.
2.
const requireCustomFile = require.context('./', false, /config.local.js$/);
requireCustomFile.keys().forEach(fileName => {
requireCustomFile(fileName);
});
does not work.
3.
export const config = require('./config.local.js') || {default:'config = {...}'}
does not work.
4.
Using .env and settings environment variable: I need to override whole array of configuration values. Not one by one.
This solution uses process.argv. It is native to node as documented here and does not use .env
It inspects the command values used to start the app. Since these should be different between your local and production environments, it's an easy way to switch with no additional modules required.
command prompt to start your node app:
(this might also be in package.json and incurred via npm start if you're using that approach.)
$ node index.js local
index.js of your node app:
var express = require('express');
var config = require('./config');
if (process.argv[2] === 'local') {
// the 3rd argument provided at startup (2nd index) was 'local', so here we are!
config = require('./config_local');
}
var app = express();
// rest of owl…

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

Npm CLI global variable

I am developing a CLI and it is all based on a uid that i have to store somehow. What is the most viable solution. I have tried with using fs but the file created was placed in the path in which the command is ran.
#!/usr/bin/env node
const program = require("commander");
const { saveUid } = require("./commands");
program
.command('setuid <uid>')
.alias('b')
.description('Set the uid of the album.')
.action(uid => {
saveUid(uid);
})
program.parse(process.argv);
So, any idea to for the saveUid function?
const saveUid = (uid) => {
}
module.exports = {
saveUid
}
You can use the mkdirp module on NPM to make a folder in any directory. Once you open the directory you can use fs to make a file in it.

Undefined process.env variable with dotenv and nodejs

I have a problem with the dotenv package.
My application folder:
|_app_folder
|_app.js
|_password.env
|_package.json
I've of course install dotenv, but when i tried to log a process.env variables, the result is always undefined, please can you help me ?
password.env :
//password.env
CLIENT_ID=xxxxxxxx
app.js :
//app.js
const express = require('express');
const app = express();
const Twig = require("twig");
//Require dotenv
require('dotenv').config();
// Setting the Twig options
app.set("twig options", {
allow_async: true,
strict_variables: false
});
app.get('/', function (req, res) {
//Trying to log it
console.log(process.env.CLIENT_ID);
//
res.render('index.twig', {
date : new Date().toString()
});
});
app.get('/instagram',function(req,res){
// Building the URL
let url = 'https://api.instagram.com/oauth/authorize/?client_id=';
// Redirect to instagram for oauth
res.redirect(url);
})
app.listen(3000, function () {
console.log('Running');
})
Thank you for your time.
By default the dotenv package does only load a file named .env if you want to load another file you need to specify the path
require("dotenv").config({ path: "path/to/file" })
Resources:
https://www.npmjs.com/package/dotenv
I was having somewhat the same problem for a while turns out you just have to put the .env file in the root of the directory (top-most level).
I know this post is old but I just want to make sure no one struggles with such a simple task again.
When using import instead of require. -
You can use -r (require) to preload dotenv. You do not need to require and load dotenv in your application code.
$ node -r dotenv/config app.js
Even though I put the .env file in the root folder, still console.log(process.env.myKey) is undefined. The fix worked for me is I put the path to the env file in the require config itself like below. (It's in the root of the file - so "./.env)
require("dotenv").config({path:"./.env"})
Another important note:
Place your .env file in the root folder, not in /src

Categories