Cannot reach key from .env file - javascript

I'm on React.Js and using emailjs to manage contact form. In order to sends the form, I must fill the user-id and template-id. But I don't want it to be visible so I put it on the .env file like that:
REACT_APP_USER_ID= user_id
REACT_APP_TEMPLATE_ID= template_id
To pass these values easely in the sendForm() property, I've put them on variables :
(useContact.jsx)
const template = REACT_APP_TEMPLATE_ID
const user = REACT_APP_USER_ID
But unfortunately with this config the form is not sent.
my folder architecture
[.env, package.json, .gitignore, src/Components/Contact/useContact.jsx]
It works when pass the raw version of the values.
Thank You.

You can access the environment variables by accessing process.env variable like this
const template = process.env.REACT_APP_TEMPLATE_ID
const user = process.env.REACT_APP_USER_ID
Note: you have to restart the server after updating .env file

Env variables are accessible through process.env
It depends how are you loading your .env file, I would suggest you to take a look at dotenv package in order to load your env files
An example you could follow it's the one from this stackoverflow answer

Related

What's the proper way of setting environment variable in Netlify functions?

What's the proper way of setting environment variables in netlify? I would like to be able to set different values for the variables depending on the environment.
Pseudo code:
let host;
if (process.env.GATSBY_CUSTOM_CONTEXT === 'production') {
host = process.env.PRODUCTION_HOST
} else if (process.env.GATSBY_CUSTOM_CONTEXT === 'development') {
host = process.env.DEVELOPMENT_HOST
}
I have tried passing env variable thru CLI, like GATSBY_CUSTOM_CONTEXT=production gatsby build and I also tried using same command with cross-env.
My other attempt used netlify.toml:
[build]
base = "/"
publish = "public"
command = "yarn build"
functions = "src/functions"
[context.production]
[context.production.environment]
GATSBY_CUSTOM_CONTEXT = "production"
All of these options worked with netlify dev locally, but in production GATSBY_CUSTOM_CONTEXT is always undefined.
The reason you can't resolve the environment variables in your Netlify functions is because as of the time of your question, Netlify does not transfer the environment variables from the netlify.toml file.
You must put them into the admin panel in your site settings in the app.netlify.com dashboard.
Unfortunately, what you're looking to doesn't seem to be currently supported. Though they provide an alternative approach.
I found this snippet on their docs:
CALLING ENVIRONMENT VARIABLES
Using environment variables directly as
values ($VARIABLENAME) in your netlify.toml file is not supported.
However, the following workflow can be used to substitute values in
the file with environment variable values, assuming you are only
trying to change headers or redirects. The rest of the file is read
BEFORE your build — but those sections are read AFTER the build
process.
Add a placeholder like HEADER_PLACEHOLDER somewhere in the netlify.toml redirects or headers sections.
Create an environment variable, for example PROD_API_LOCATION, with the desired value. You can create environment variables in the
toml file or in our UI. You might use the latter to keep sensitive
values out of your repository.
Prepend a replacement command to your build command. Here’s an example for a site using yarn build to build: sed -i
s/HEADER_PLACEHOLDER/${PROD_API_LOCATION}/g netlify.toml && yarn build
Taken from here: https://www.netlify.com/docs/netlify-toml-reference/

Getting Facebook Messenger Page_Access_Token in .env

According to Facebook Guide line, I was told to create a .env file to store the Page_Access_Token
The content in .env is:
PAGE_ACCESS_TOKEN="XXXXXXXXXXXXXXXXX"
and we have an app.js that included:
const PAGE_ACCESS_TOKEN = process.env.PAGE_ACCESS_TOKEN;
However, when I console.log(process.env.PAGE_ACCESS_TOKEN); it returns me an undefined
Can advise how to fix this problem?
P.S. I am using windows and ngrok to test
.env without any configurations or tools does nothing, unless your told your app to, this is just a basic file.
However if you really want to use a .env to store your environment variables, you may need something like this dotenv

Properties file in JavaScript / Angular

In Java I usually create application.properties in my resource folder and put configs in there.
And when I need it I just do Properties prop = new Properties(); prop.load(... my file) and then use prop.getProperty("Something")
I want to do something similar in Javascript
In my js code I have this:
// REST API Base URL
var baseUrl = "http://localhost:8083/api";
I want this to be in a application.properties file and then load the value.
How can I achive this?
Thanks
In angular 2+ projects and for a good practices you should create environments folder with one file per env like: environment.js, environment.prod.js.
and into file you can export a constant or by default like that
export const environment = {
apiUrl: '',
googleApiKey: '',
}
and you can import this environment in every file you will needed like
import { environment } from '{relativePath}/environment/environment.js'
If you create different files for every env like prod. You need to replace environment.js for env that you will be build. You have lot of info about this with webpack or other compilers.
I recommend you strongly to develop into a common.js project. It will be more friendly for you importing modules and you will have powerful possibilities of scalable app.
But the easy(Ugly) solution is:
index.html
<head>
<script src="environment.js">
<script src="app.js">
</head>
environment.js
// Declaring environment like that you will have window scoped the variable
// and you will have global access to environment with window.environment
var environment = {apiUrl: 'https://api.url:4100'}
app.js
function example(){
console.log(window.environment.apiUrl); // out https://api.url:4100
}
The approach depends on how you build and/or bundle your AngularJs application. But regardless of that, you'll need to create a config.json file to contain your settings.
If using browserify or webpack, you can import that file via require(...), otherwise you can simply request it via ajax before your app bootstraps.
In any of these cases, the best way to use the configuration data throughout your app is to define it as a constant at the bootstrap phase: app.constant('CONFIG', configData);, assuming that configData is a variable that contains the data from your config.json file.
Then you can use dependency injection to provide CONFIG to all your controllers, services and directives.

Retrieve config and env variable in vue component

I have a Vue component in my Laravel application.
I want to retrieve a URL that is in a config (or the .env Laravel file) directly in my Vue component, instead of hardcoding it.
In webpack laravel mix I can retrieve my .env variable like this.
require('dotenv').config()
let proxyUrl = process.env.APP_URL
But when I want to do this in my app.js, I have a can't resolve fs when trying to require dotenv.
What is the best way to have this data available in my Vue components ?
To access your env variables in a Vue Component file in Laravel, you will need to prefix your variable with MIX_.
In the .env file
To take your case as an example, if you intend to use APP_URL as a variable in your .env file, instead of APP_URL, you should use MIX_APP_URL like:
MIX_APP_URL=http://example.com
In your Vue Component file
You then access the variable by using the process.env object in your script like:
process.env.MIX_APP_URL
Say today you set a property named proxyUrl and assign the variable as its value, in your script in the .vue file, the code should look like:
export default {
data () {
return {
proxyUrl: process.env.MIX_APP_URL,
},
}
}
After that you should be able to retrieve the property in your vue template as normal like:
<template>
<div>
//To print the value out
<p>{{proxyUrl}}</p>
// To access proxyUrl and bind it to an attribute
<div :url='proxyUrl'>Example as an attribute</div>
</div>
</template>
Here is the official doc released in Laravel 8.x, in case you want to have a look.
I had this same issue, but placing the variable in blade was not an options for me, also it meant having a variable declare in a blade file and then use in a javascript file which seems a bit unorganized. So if you are in this same position then I think there is a better solution. If you are using Vue you most likely are compiling your files using Laravel mix.
If this is the case you can inject environment variables into Mix, you just need to add the prefix MIX_. So you can add to your .env file a variable like:
MIX_SENTRY_DSN_PUBLIC=http://example.com
and then access this variable like this in your javascript file:
process.env.MIX_SENTRY_DSN_PUBLIC
you can access this anywhere in your pre compile file. You can find this information in the laravel documentation. https://laravel.com/docs/5.6/mix#environment-variables
IMPORTANT
You have to reload the bundle for the changes to take effect.
Mine didn't work until I killed the dev bundle and re-ran npm run watch.
You can do this in Blade template:
let window.something = {{ config('seme_config.something') }}
Then just use the variable in JS with:
window.something
Also, you shouldn't use env() helper directly. Extract data from config file only.

Node.js: How to setup different variables for prod and staging

I'm using Express and I need to use different credentials for each server (staging and production).
I could setup the variables in the server.coffee file but then I'd need to access those variables in different files.
server.coffee:
app.configure 'production', () ->
app.use express.errorHandler()
What's the solution? Setup the variables and then export them?
./config.js
var development = {
appAddress : '127.0.0.1:3000',
socketPort : 4000,
socketHost : '127.0.0.1',
env : global.process.env.NODE_ENV || 'development'
};
var production = {
appAddress : 'someDomain.com',
socketPort : 4000,
socketHost : '8.8.8.8',
env : global.process.env.NODE_ENV || 'production'
};
exports.Config = global.process.env.NODE_ENV === 'production' ? production : development;
./app.js
var cfg = require('./config').Config;
if (cfg.something) { // switch on environment
// your logic
}
This might be a good place to use npm-config.
When running scripts (see npm-scripts(7)) the package.json "config" keys are overwritten in the environment if there is a config param of <name>[#<version>]:<key>
I would not use them for every type of variable configuration setting, but I think it's a good solution for simple cases like URLs and ports because:
You put them directly into package.json.
In addition, you can specify them on the command line or as ENV variables.
Anything run through npm can refer to them (e.g., scripts).
You can set them per-user with `npm config set foo:port 80
The one caveat is that the config parameter in your package.json is only automatically exported into the environment when you run your code through npm. So, if you just run it with node, like, node ./myapp.js, then you can't expect that process.env.npm_package_config_foo will contain your value. However, you can always var pkg = require('./package.json'); and access the values at pkg.config.
Because it might not be immediately obvious, I'd also add that the npm_package_config environment variables do not bubble up to apps that depend on your npm package. So, if your depended-on package refers to process.env.npm_package_config_foo, then the dependent package would have to define that in its own package.json. I guess since it's an "npm_package_config" it wouldn't make sense to push them all the way up the tree.
So, how would I use one npm config variable and have it work all the way up the tree, in both the base package and the packages that depend on it? It's actually a little confusing, and I had to figure this out through trial and error.
Let's say you have a package connector and package client. client depends on connector and you want to specify a config parameter for connector that can be used or overwritten in client. If you use process.env.npm_package_config.port in your connector module, then when it's depended on in client module, then that variable won't be exported and it will end up as undefined.
However, if you instead use process.env.npm_config_connector_port (notice the first one starts with npm_package_config and the other with npm_config_packagename), then you can at least set that in your .npmrc using npm config set connector:port 80 and it will be "namespaced" as process.env.npm__config_connector_port everywhere that you run npm, including scripts that you run in client that depend on connector, and you'll always be able to overwrite it on the command line, in your ENV, or in your .npmrc. You just have to keep in mind that, as with any environment variable, it may not always be set. So, I would use the default operator with the process.env.npm_config_connector_port as the first (preferred) value:
var port = process.env.npm_config_connector_port || sane_default
Here, sane_default could be populated from one of the other recommended methods. Personally, I like keeping configuration data like these in JSON files at the very least, and package.json seems like the best JSON file to put them in. Store them in data instead of code and then you can easily use the static JSON in-line, generate them dynamically, or pull them from the filesystem, URLs or databases.
I have uploaded an implementation into https://github.com/qiangyu/nodejsconfig. I believe it will satisfy your needs. Basically, you only need to provide one configuration file:
dev.appAddress = '127.0.0.1:3000';
prod.appAddress = 'someDomain.com';
Then, you use following code to read the appAddress in prod environments:
var xnconfig = require('nodejsconfig');
var fs = require('fs');
var data = fs.readFileSync(__dirname+"/config.properties", "UTF8");
// assume we will be using environment "prod"
var config = xnconfig.parse("prod", data);
// the output will be someDomain.com
console.log(config.getConfig("appAddress"));
If you don't want the logic for determining which config to use in each file (which would look pretty ugly), you'll have to export it somewhere.
What I would suggest: Have a config.json file containing the different configs. The main file requires it and does something like config.default = config.(condition ? 'production':'development'). In all other files, you can now just do require('./config').default.
I have an app which uses three different methods of declaring config variables (uris, api keys, credentials, etc.) depending upon the environment (production = environment variables; staging = command line args; local = config files.)
I wrote a little "config" module to handle merging all of these options into one object that I can use in my app and uploaded it as a gist: https://gist.github.com/1616583
It might not be the best implementation, but it's been working pretty well so far :).

Categories

Resources