So I'm trying to understand how to use .env to secure my api key & data for my login auth. I've followed the process of the dotenv package and the stackoverflow answer here.
What I did:
1. I installed the dotenv package
2. In my rootfolder, I added a .env with only one line:
API_AUTH=http://myapilink.com
3. In my App.js, I added following line:
require('dotenv').config()
console.log(process.env.API_AUTH)
However, console.log returns 'undefined', why is that? What have I missed?
You have to prefix your environment variables with REACT_APP_. See here.
Note: You must create custom environment variables beginning with
REACT_APP_. Any other variables except NODE_ENV will be ignored to
avoid accidentally exposing a private key on the machine that could
have the same name. Changing any environment variables will require
you to restart the development server if it is running.
So instead of just API_AUTH it would be REACT_APP_API_AUTH instead.
And it will be exposed to your app as process.env.REACT_APP_API_AUTH.
Dotenv only works on server side. It needs an environment to store the variables. Here, we extract the content of the .env file and reduce it to an Object and pass it to Webpack's DefinePlugin allowing us later usage (process.env.API_AUTH):
const webpack = require('webpack');
const dotenv = require('dotenv');
module.exports = () => {
const env = dotenv.config().parsed,
envKeys = Object.keys(env).reduce((prev, next) => {
prev[`process.env.${next}`] = JSON.stringify(env[next]);
return prev;
}, {});
return {
plugins: [
new webpack.DefinePlugin(envKeys)
]
};
Related
Does anyone know how to change the names of the build's generated JS files, without using webpack? ex: every time you have a build change the filenames: 'bundle_v1.js', 'chunk_v2.js' (It doesn't necessarily need to be standardized).
Context: every time we publish our project through Azure, whether in development or production environment, we need to ctrl+f5 to clear the cache and show the changes.
I've already tried to add some configs in the config-overrides.js file but I wasn't successful.
Myconfig-overrides.js:
const {
addBabelPlugin,
override,
} = require('customize-cra');
const path = require('path');
module.exports = override(
addBabelPlugin([
'babel-plugin-root-import',
{
rootPathPrefix: '#/',
rootPathSuffix: 'src',
},
]),
);
export const EnvironmentProvider: React.FC<EnvironmentProps> = ({ children }) => (
<EnvironmentContext.Provider value={{
APP_NAME: import.meta.env.VITE_APP_NAME,
GQL_URI: import.meta.env.VITE_GQL_URI
}}>
{ children }
</EnvironmentContext.Provider>
)
when using import.meta to load env variables vscode only recognize url variable... so how i can tell typescript that there are custom variables in import.meta?
Maybe this is what you want 智能提示, but only Chinese website has the section now.
In a word, you can create /src/env.d.ts like this:
interface ImportMetaEnv {
VITE_APP_NAME: string;
VITE_GQL_URI: string;
// others...
}
as you would normally do with react project , create .env file in your root project and put .env in .gitignore so that you don't push important data on git by mistake .
next thing to do is that defining variable with prefix VITE instead of REACT_APP , like below
VITE_BASE_URL=http://localhost:7000
VITE_DB_PASSWORD=123
when you are done with defining your environment variable , you can use them in the project like this
export const BASE_URL = `${import.meta.env.VITE_BASE_URL}/api`
run the project and it should be working , otherwise stop the server and restart , it should solve your problem .
if you think that your problem is still not solved , you should checkout vite doc : https://vitejs.dev/guide/env-and-mode.html
I would like to know how to apply google analytics id for staging/local and production,
I have two ID's, each for staging/local and production. I am using nodejs as a backend, and stored the google analytics key in config file using env file
how to pass if local, pass google analytics id ga_local
if prod, pass google analytics id ga_pro in nodejs in the startup
app.js
var express = require('express');
var config = require('./config');
var app = express();
var ga_id = app.get('env');
ga_id == "development" ? config.ga_local : config.ga_pro;
//how to pass to frontend
.env
ga_local = "UA-XXXX-X",
ga_pro = "UA-YYYY-Y"
config.js
require('dotenv').config();
const config = {
ga_local: process.env.ga_local,
ga_pro: process.env.ga_pro
};
module.exports = config;
front end
<script async src='https://www.googletagmanager.com/gtag/js?id=${ga_id}'></script>
you can provide mode at the time of running your node server. .
Run your file -> node index.js -m prod
code to access command line arguments.
const program = require('commander');
/* reading commandline parameters */
program
.version('1.2')
.option('-m,--mode [type]', 'Running Mode', 'MODE_NOT_PROVIDED')
.parse(process.argv);
console.log(program.mode); local,prod or dev
I have a different URL for our api depending if it's development or production for a react app.
Using webpack, how can I set an env var like __API_URL__ and then change that depending if it's built using webpack.config.dev vs webpack.config.prod
I thought the answer may be in webpack.DefinePlugin but no luck.
new webpack.DefinePlugin({
__API_URL__: 'localhost:3005',
}),
I'd expect __API_URL__ to be available as a global but no such luck.
What would be the right way to do this? Also key thing is that no express server on the prod deploy. So this has to happen during the build...
As Michael Rasoahaingo said, the DefinePlugin works similar like replacing values with regular expressions: It replaces the value literally in your source code. I would not recommend to use the DefinePlugin for this kind of task.
If you want to switch configs based on the environment, you could use resolve.alias for that. Just import your config like this:
var config = require("config");
and then add a mapping in your webpack.config.js:
resolve: {
alias: {
config$: require.resolve("path/to/real/config/file")
}
}
DefinePlugin is not working as you expected. It doesn't expose __API_URL__ as a global variable.
According to the documentation: "The values will be inlined into the code which allows a minification pass to remove the redundant conditional."
So, it will find all occurence of __API_URL__ and changes it.
var apiUrl = __API_URL__
and
__API_URL__: '"localhost:3005"' // note the ' and "
become
var apiUrl = "localhost:3005"
I was referring to how angular js connects to mongo db. So while setting the url and port for the 'db' object, I found code like below:
var path = require('path'),
rootPath = path.normalize(__dirname + '/../..');
module.exports = {
root: rootPath,
port: process.env.PORT || 3000,
db: process.env.MONGOHQ_URL
}
Will someone please let me know what is this path here for? And also, what is the default value of MONGOHQ_URL here?
From the link http://docs.mongohq.com/languages/nodejs.html , I came to know mongo url can be set to :
var MONGOHQ_URL="mongodb://user:pass#server.mongohq.com:port_name/db_name"
Am I right?
Thanks,
Sabari
The MONGOHQ_URL in your code snippet comes from the shell environment. For example, in bash you would add that to your ~/.bash_profile:
export MONGOHQ_URL="mongodb://user:pass#server.mongohq.com:port_name/db_name"
... or include on your command line when starting the node app:
MONGOHQ_URL="mongodb://user:pass#server.mongohq.com:port_name/db_name" node app.js
Another common approach with Node.js is to use something like dotenv, which will load environment variables from a .env directory in your project.
And also, what is the default value of MONGOHQ_URL here?
There is no default; you need to define this if you want to connect to a MongoHQ instance.