How to use Azure Pipeline variable in JavaScript (React) project? - javascript

How do I use variable defined for the pipeline in React Project?
Currently, I have build variable defined in the .yml file like that
variables:
src: "virtual-furnace-app"
dest: "$(src)/build"
REACT_APP_VERSION: $(Build.BuildNumber)
and in the front end code, I have tried to accessing it like that but it is undefined
export const REACT_APP_VERSION = process.env.NODE_ENV === "development" ? `v${pjson.version} (Development build)` : `v${pjson.version} (${process.env.REACT_APP_VERSION})` ;

After while I found solution myself.
So in the code, I check if we are on localhost NODE_ENV === development and if not I will read variable injected to React script process.env.REACT_APP_VERSION
import pjson from "../../package.json"
export const REACT_APP_VERSION = process.env.NODE_ENV === "development" ? `v${pjson.version} (Development build)` : `v${pjson.version} (${process.env.REACT_APP_VERSION})` ;
Azure Pipeline yml code
REACT_APP_VERSION=$(BuildID) yarn build

How to use Azure Pipeline variable in JavaScript (React) project?
You could try to use a .env file to store the variables, then use them in a React Native app.
You can reference this blog for details : How to gracefully use Environment Variables in a React Native app.
Also find some similar threads in SO, you can reference them can check if that helps:
Azure Devops Variable Substitution for Frontend js applications
How to use environment variables in React app hosted in Azure
Besides, you could also try to set REACT_APP_VERSION in the start of your script as well, e.g. "scripts": { "start": "cross-env REACT_APP_VERSION=$REACT_APP_VERSION react-scripts start" }

Related

process.env variables undefined React App - Not using create-react-app

I have a custom React app, and it's not using create-react-app. Problem is I can use dotenv and environment variables locally via .env file but when in production process.env is undefined entirely.
I don't know how to get it working. I've added the environment variables to my server in Google Cloud but process.env itself is not even defined, the same code that worked locally does not work on a virtual prod server.
So for example something like this works locally but not in production:
if (process.env.NODE_ENV === 'development') {
response = await request.post(process.env.GRAPHQ_LOCAL).send(query);
} else {
response = await request.post(process.env.GRAPHQL_PROD).send(query);
}
Your project starter file add dotenv init...
if you install this package, should be work
require('dotenv').config()

Quasar - Support multiple environments

I’m trying to create project with multiple environments: staging, prod, test + development obviously.
With Vuejs that’s pretty straightforward
vue-cli-service build --mode staging
And create .env.staging file.
Important note that process.env should be accessed from quasar.conf file in order to set different publicPath for each env.
How can I achieve this behavior at Quasar?
Thanks
Check out the #quasar/qenv extension it seems to support multiple environments. https://github.com/quasarframework/app-extension-qenv
Another approach, as I am using Firebase Hosting and both staging and production hosting is in the same project ... I had the idea of using quasar build -d (debug mode) as staging and quasar build as production, each with its own dist folder, and I set a DEPLOY_MODE env variable in quasar.conf.js accordingly:
build: {
distDir: ctx.debug ? `dist/${ctx.modeName}-dev` : `dist/${ctx.modeName}`,
env: {
DEPLOY_MODE: ctx.prod && !ctx.debug ? 'PRODUCTION' : (ctx.prod && ctx.debug ? 'STAGING' : 'DEV')
},
...
I used the dotenv extension and have an .env.prod and .env.dev file. Within .env.prod I define the production and staging specific keys, e.g. API_KEY=blah, API_STAGING_KEY=blah, then in my boot file, I use process.env.DEPLOY_MODE to determine which keys to use in my
production env file.
if(process.env.DEPLOY_MODE === 'staging') {
const API_KEY = process.env.API_STAGING_KEY
} else {
const API_KEY = process.env.API_KEY
}
I suspect #qenv is more elegant but this was enough for my simple project.

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/

Setting default environment variables in Heroku

I'm working on an app that connects to third-party APIs which require the use of an APP ID and SECRET KEY.
I am storing these values as environment variables in heroku, so that I don't need to expose them in my code.
If I deploy to heroku, it will use heroku's environment variables to resolve these API credentials.
If I'm working on it locally, I want to use my config.js module, and lookup the API credentials there. NOTE: This config.js file is included in my .gitignore so that these credentials never end up in the cloud.
The problematic code is this:
var api_secret = process.env.API_SECRET || require('../../config.js').secret;
When I run this locally, I've got no issues. Meaning, it is unable to resolve the environment variable, so instead it uses the secret from within config.js.
When I run it on heroku, it DOES throw an error telling me that module 'config.js' could not be found. This makes sense, because it was never pushed up with the rest of the repo, by virtue that it is in my .gitignore.
Because heroku is parsing through my code before it ever runs, the require('../../config.js') is problematic. It is trying to lookup a file that doesn't exist.
How can I solve the issue of using environment variables when deployed, and the config.js module when running locally?
On the Heroku dashboard for your application, you can set config variables. If you have the Heroku Toolbelt set up on your machine, you can also use:
heroku config:set API_SECRET=secret
See this article for more.
Edit: Think I may have misunderstood the question. I would suggest, if possible, using the dotenv npm package to set your config variables locally.
If not, another thing to check would be that the config.js package is in your package.json file, because Heroku will use this to build your dependencies.
If you do not want to push your config.js to heroky at all, you can just follow the following to determine whether the config file exists or not with a try catch and the file system module:
Check synchronously if file/directory exists in Node.js
In your case:
var fs = require('fs'),
api_secret,
config;
try {
// Check whether config.js exists
config = fs.lstatSync('../../config.js');
// If we reach this line then config.js exists, yay!
api_secret = process.env.API_SECRET || require('../../config.js').secret;
// or alternatively api_secret = require('../../config.js').secret;
// depending on your logic
}
catch (e) {
// else config.js does not exist
api_secret = process.env.API_SECRET
}
To run Heroku commands programmatically, you can set up a free Ruby app and make it do what you want through API calls. Use Heroku-api. See https://github.com/heroku/heroku.rb
If you want to set Heroku commands manually, you can set env variables on Heroku either with the command heroku config:set MYVAR=MYVALUE or through the Heroku dashboard (Click on your app > settings > reveal config vars > edit).

How do you detect the environment in an express.js app?

How do you detect what environment an expressJS app is running in? (development, test, production?). There's nothing in process.env indicating an environment...
I'm aware that you can declare variables in your configuration file under each environment, but that doesn't help if you are dynamically loading modules...
You can either check the environment by checking the app.settings.env (this will work in Express), or you can do it in a more direct way by checking process.env.NODE_ENV (the environment is the one found in that variable or 'development' by default < this also works in other libraries such as Socket.IO etc).
app.get('env') would also return the environment.
if ( app.get('env') === 'development' ) {
app.use(express.errorHandler());
}
I'd like to address a straightforward way to passing NODE_ENV variables to your node script in order to access them in process.env
"scripts": {
"start": "./node_modules/.bin/cross-env NODE_ENV=development ./node_modules/.bin/nodemon server.js",
"debug": "./node_modules/.bin/cross-env NODE_ENV=development ./node_modules/.bin/nodemon --debug server.js",
"test": "./node_modules/.bin/cross-env NODE_ENV=test ./node_modules/.bin/babel-tape-runner test/test-*.js"
},
can be used as
if ( app.get('env') === 'development' ) {
app.use(express.errorHandler());
}
The can detect which environment you are in by inspecting app.settings.env.
cannot access the nodejs server. can detect node env from express using app.setting.env
var app = express();
app.setting.env render to the template engine.
check from the browser.
There are a lot of useful recommendations in other answers. I'm generally doing it like this:
const environment = process.env.NODE_ENV || 'development';
The good thing is that such approach is not specific to Express per se, but actually is an accepted practice in wider Node.js ecosystem.
Also, I've implemented a reusable module, which allows to automatically detect environment by analyzing both CLI arguments and NODE_ENV variable. This could be useful on your development machine, because you can easily change environment by passing a CLI argument to you Node.js program like this: $ node app.js --prod.
Please see more details and use cases on the detect-environment's page.

Categories

Resources