How to set NODE_ENV on Amplify for React app - reactjs

I am trying to run multiple environments of an AWS Amplify react app. So have set up a single environment, created two versions pointing to a master and a staging branch of GIT, assigned them to two different domains, and all working.
However, now I need to start one as production and one as staging so dotenv will read .env.production and .env.staging. (which is my actual objective :) )
So I set up an environment variable called NODE_ENV and set it to staging and production. However, Amplify seems to ignore it, and if I print out the environment variables, I get production on both systems
And the output from console.log(process.env)
Object
FAST_REFRESH: true
NODE_ENV: "production"
PUBLIC_URL: ""

OK, so I may have found a solution, it AIN'T pretty, but it works for me.
My solution is
Create two files,
env.production
env.stagign
Notice the missing .
They will be like your good old .env files
REACT_APP_VARIABLE=VALUE
Then you create an environment variable called BUILD_ENV like above, with an override. In my case, I have a master and staging based on the git branches.
The ugly magic comes in the build script. In amplify.yml we'll add BUILD_ENV, one line to write it, because I had a lot of problems getting it to work.
The second is that we add a new build type, called build:$BUILD_ENV
version: 2
frontend:
phases:
preBuild:
commands:
- npm ci
build:
commands:
- echo "Build environment is ${BUILD_ENV}"
- npm run build:${BUILD_ENV}
artifacts:
baseDirectory: build
files:
- '**/*'
cache:
paths:
- node_modules/**/*
The last step is that we need to get around that react build cares little about what you want to do, so we'll just build production, but with our env. So we will copy the relevant env.environment to .env.production I told you it would be ugly :)
"scripts": {
"start": "PORT=8082 react-scripts start",
"build": "react-scripts build",
"build:staging": "cp env.staging .env.production && NODE_ENV=staging react-scripts build",
"build:production": "cp env.production .env.production && react-scripts build",
=========================================
So the problem is (I think) that between react, node, AWS amplify, there are a lot of people who feel that things should be in very specific ways, like react deciding that there can only be production and dev, and amplify limiting what we're allowed to do to the environment in regards to variables.
This is probably not the right way of doing this, but it DOES work, so that's OK?

Related

Create-react app integration with django backend vs babel and webpack pipeline

I've been trying to get up a react and django application. First, I had followed this set of videos here: https://www.youtube.com/watch?v=6c2NqDyxppU&list=PLzMcBGfZo4-kCLWnGmK0jUBmGLaJxvi4j&index=3. There was a bunch of commands that you can see in the description that needed to be run in as well as a lot of copy pasting configuration files.
Later, my friend told me that create-react-app existed and would set up everything needed with just one command. I tried it, and it worked really well. However, there were issues with connecting it to django. The files that came out of create-react-app were different to the ones shown in the video and when I tried searching it up, a few solutions said to use npm run build and pass the build folder into django.
Running a build takes quite a long time and it is not automatic as it was when I had the webpack and babel system. What am I supposed to do to configure create-react-app so that I can get it to update automatically and get it into django.
Some places said that I could edit the config files when I do npm run eject. There is a problem that the package.json files in the tutorial project and the create-react-app project are not the same. The thing that lets the webpack and babel project update is this snippet of code in the package.json file:
"scripts": {
"dev": "webpack --mode development --watch",
"build": "webpack --mode production"
},
I ejected my create-react-app project but create-react-app doesn't use webpack so I won't be able to use this. What do I do?

REACT env variables

I am trying to setup a project for staging between dev to prod. I am trying to follow this article as it seems kind simple just to have a config file.
https://serverless-stack.com/chapters/manage-environments-in-create-react-app.html
However early in the article he states you set the variable by doing this:
REACT_APP_TEST_VAR=123 npm start
When i start by app like that I get following:
The term 'REACT_APP_STAGE=123' is not recognized as the name of a cmdlet, function. Any pointers?
I also tried:
you need to put the "REACT_APP_TEST_VAR=123" inside the script of npm start. For example when I run a npm build command it runs the following command (Where ENVIRONMENT is a env variable):
ENVIRONMENT=production webpack --mode production
So let's assume your cnpm start runs the regular "react-scripts start". You should define in your package json that the script "start" will do "REACT_APP_TEST_VAR=123 react-scripts start":
"start": "REACT_APP_TEST_VAR=123 react-scripts start",

Set react-scripts test environment file

We're using react-scripts to run our tests, via the command react-scripts test. Locally we have our own test environments, and use the .env.test file as the environment file (it uses this automatically).
However, in our CircleCI environment we want to run the tests using the development environment, i.e. using .env.development. I can't figure out how to tell react-scripts to use the dev env file, I've tried setting various values before running the command like REACT_APP_ENV and NODE_ENV. I've tried using the env-cmd module to specify it to use the dev env file (e.g. env-cmd .env.development react-scripts test), but it STILL uses the test one.
I know in the CircleCI test command I could just overwrite the test env file with the dev one (something like cp -rf .env.development .env.test && react-scripts test), but I was wondering if there was a cleaner way of doing it (since if I did it that way, if we wanted to test using dev environment locally, it'd overwrite our personal .env.test files)?
The only thing you need to do is to modify the react-scripts test command by adding the following:
--env=jsdom
So the end result would be
// package.json
{
"scripts": {
...
"test": "react-scripts test --env=jsdom"
...
}
}
https://serverless-stack.com/chapters/environments-in-create-react-app.html

What exactly is the 'react-scripts start' command?

I've been working with a React project using create-react-app and I have two options to start the project:
First way:
npm run start with the definition at the package.json like this:
"start": "react-scripts start",
Second way:
npm start
What is the difference between these two commands? And, what is the purpose of the react-scripts start?
I tried to find the definition, but I just found a package with this name. I still don't know what is the use of this command?
create-react-app and react-scripts
react-scripts is a set of scripts from the create-react-app starter pack. create-react-app helps you kick off projects without configuring, so you do not have to setup your project by yourself.
react-scripts start sets up the development environment and starts a server, as well as hot module reloading. You can read here to see what everything it does for you.
with create-react-app you have following features out of the box.
React, JSX, ES6, and Flow syntax support.
Language extras beyond ES6 like the object spread operator.
Autoprefixed CSS, so you don’t need -webkit- or other prefixes.
A fast interactive unit test runner with built-in support for coverage reporting.
A live development server that warns about common mistakes.
A build script to bundle JS, CSS, and images for production, with hashes and sourcemaps.
An offline-first service worker and a web app manifest, meeting all the Progressive Web App criteria.
Hassle-free updates for the above tools with a single dependency.
npm scripts
npm start is a shortcut for npm run start.
npm run is used to run scripts that you define in the scripts object of your package.json
if there is no start key in the scripts object, it will default to node server.js
Sometimes you want to do more than the react scripts gives you, in this case you can do react-scripts eject. This will transform your project from a "managed" state into a not managed state, where you have full control over dependencies, build scripts and other configurations.
As Sagiv b.g. pointed out, the npm start command is a shortcut for npm run start. I just wanted to add a real-life example to clarify it a bit more.
The setup below comes from the create-react-app github repo. The package.json defines a bunch of scripts which define the actual flow.
"scripts": {
"start": "npm-run-all -p watch-css start-js",
"build": "npm run build-css && react-scripts build",
"watch-css": "npm run build-css && node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/ --watch --recursive",
"build-css": "node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/",
"start-js": "react-scripts start"
},
For clarity, I added a diagram.
The blue boxes are references to scripts, all of which you could executed directly with an npm run <script-name> command. But as you can see, actually there are only 2 practical flows:
npm run start
npm run build
The grey boxes are commands which can be executed from the command line.
So, for instance, if you run npm start (or npm run start) that actually translate to the npm-run-all -p watch-css start-js command, which is executed from the commandline.
In my case, I have this special npm-run-all command, which is a popular plugin that searches for scripts that start with "build:", and executes all of those. I actually don't have any that match that pattern. But it can also be used to run multiple commands in parallel, which it does here, using the -p <command1> <command2> switch. So, here it executes 2 scripts, i.e. watch-css and start-js. (Those last mentioned scripts are watchers which monitor file changes, and will only finish when killed.)
The watch-css makes sure that the *.scss files are translated to *.cssfiles, and looks for future updates.
The start-js points to the react-scripts start which hosts the website in a development mode.
In conclusion, the npm start command is configurable. If you want to know what it does, then you have to check the package.json file. (and you may want to make a little diagram when things get complicated).
succinctly - it runs this
node node_modules/react-scripts/bin/react-scripts.js start
"start" is a name of a script, in npm you run scripts like this npm run scriptName, npm start is also a short for npm run start
As for "react-scripts" this is a script related specifically to create-react-app
npm start is the short form for npm run start
You can check about it here Difference between npm start and npm run start
react-scripts start
react-scripts is a set of scripts to support the creation, development and testing of react applications. It is used by create-react-app.
create-react-app is the officially supported way to create single-page React applications. create react app uses webpack to parse and bundle the application.
webpack parses the application and creates a dependency graph from its entry point specified in the webpack config file. while parsing, webpack uses babel to transpile the application to JavaScript, which has better support across browsers.
Webpack uses the generated dependency graph to create a single JavaScript file consisting of the application source code and modules used by the app, injects the file via script tag into public/index.html, and starts a development server on http://localhost:3000. Navigating to this URL in the browser will show a live, interactive instance of your application. Any changes saved to the source code will reflect in the running app instance automatically.
You can read more about this topic more on here

create react app not picking up .env files?

I am using create react app to bootstrap my app.
I have added two .env files .env.development and .env.production in the root.
My .env.development includes:
API_URL=http://localhost:3000/api
CALLBACK_URL=http://localhost:3005/callback
When I run my app using react-scripts start and console out process.env it spits out
{ NODE_ENV: "development", PUBLIC_URL: "" }
I've tried different things, but its just not picking up the veriables in my development file, what am I doing wrong?!
Directry structure is:
/.env.development
/src/index.js
Package.json script is:
"start": "export PORT=3005; npm-run-all --parallel server:start client:start",
"client:start": "export PORT=3005; react-scripts start",
"server:start": "node server.js",
"build": "react-scripts build",
Edit:
#jamcreencia correctly pointed out my variables should be prefixed with REACT_APP.
Edit 2
It works okay if I name the file .env but not if I use .env.development or .end.production
With create react app, you need to prefix REACT_APP_ to the variable name. ex:
REACT_APP_API_URL=http://localhost:3000/api
REACT_APP_CALLBACK_URL=http://localhost:3005/callback
** Make sure your .env file is in the root directory, not inside src folder.
CRA Docs on Adding Custom Environment Variables:
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
Make sure your .env file is in the root directory, not inside src folder.
Had this same problem! The solution was to close the connection to my node server (you can do this with CTRL + C). Then re-start your server with 'npm run start' and .env should work properly.
Source: Github
If you want to use multiple environment like .env.development .env.production
use dotenv-cli package
add .env.development and .env.production in project root folder
and your package.json
"scripts": {
"start": "react-app-rewired start",
"build-dev": "dotenv -e .env.development react-app-rewired build",
"build-prod": "dotenv -e .env.production react-app-rewired build",
"build": "react-app-rewired build",
"test": "react-app-rewired test --env=jsdom",
"eject": "react-scripts eject"
},
then build according to environment like
npm run-script build-dev
I was having the same problem, but it was because I had my .env file in YAML format instead of JS.
It was
REACT_APP_API_PATH: 'https://my.api.path'
but it needed to be
REACT_APP_API_PATH = 'https://my.api.path'
For people who apply all those answers above and didn't work just restart the terminal of npm start, stop the live server and run it again and it will work because it works for me
Regarding env-cmd. As per VMois's kind post on gitHub, env-cmd has been updated ( version 9.0.1 as of writing ), environment variables will work as follows on your React project:
"scripts": {
"build:local": "env-cmd -f ./.env.production.local npm run build",
"build:production": "env-cmd -f ./.env.production npm run build"
}
In your package.json file.
1- Make sure .env file is based your react app root directory
2- for react app you need to prefix REACT_APP_ to the variable name. ex: REACT_APP_API_URL
3- kill server and npm start again after .env file modify
For this purpose there is env-cmd module. Install via npm npm i env-cmd then in your package.json file in scripts section:
"scripts": {
"start": "env-cmd .env.development react-scripts start",
"build": "GENERATE_SOURCEMAP=false env-cmd .env.production react-scripts build",
}
In your project root you have to create two files with the same env variables but with different values:
.env.development
.env.production
Then exclude them from public. For this in your .gitignore file add two lines:
.env.development
.env.production
So this is a proper way to use different env variables for dev and prod.
While working with .env file, be it frontend or backend.
Whenever you modify the .env file, you must restart the respective server for the changes to take effect in the application.
Hot reloading doesn't read changes from .env file.
If the .env file works but .env.development or .env.production don't, then create an empty .env file alongside those two. I don't know why but this works for me.
Your project can consume variables declared in your environment as if they were declared locally in your JS files. By default you will have NODE_ENV defined for you, and any other environment variables starting with REACT_APP_.
Reference: https://create-react-app.dev/docs/adding-custom-environment-variables
that doc creates confusion.
So you actually need to put prefix REACT_APP_ within the .env to make it work.
And make sure that you restart the test/dev/prod server because the .env content change was loaded on the build stage.
And remember not to have semi-colon after the API key in the env-file.
REACT_APP_API_KEY = 'ae87cec695cc4heheh639d06c9274a';
should be
REACT_APP_API_KEY = 'ae87cec695cc44heheh1639d06c9274a'
that was my error
when you get undefined from the environment file then just stop the terminal and restarts with npm start command.
For any VS Code users, be aware that the .env.local env file is auto-sourced, but also auto-ignored from search results when you do a project wide search for MY_ENV_VAR(probably due to it being git ignored by default). This means that if you have MY_ENV_VAR= in your .env.local like me and forgot about it, it'll break things and you'll spend 15 mins being very confused.
Was struggling for a good hour before I noticed my kind IDE added an import:
import * as process from "process";
just remove it and you're fine, if that's your case as well.
After you add .env file, you need to
restart your application
kill the server
run npm start again
And it should work
I had same issue that I wasn't able to access .env variable in App.js.
and I had solved the problem use create correct .env file.
in my case I was copy file from different OS and use in ubuntu system
so just I did "sudo touch .env" and added my variables and restart app again then it's working for me.
I forget to add process.env.
It looks like this
const domain = process.env.REACT_APP_AUTH0_DOMAIN;
first step:
in your .env.local file add REACT_APP_your_API_key in this way
second step:
Add your config file ${process.env.REACT_APP_Your_API_key}
the third step:
must restart your React App and then Test whether it works.
mainly, I forget the last step
If none of the solutions above worked for you, give these potential solutions a shot:
Make sure all the import statements within the file that is requiring defined environmental variables are being imported from the local project and not some other project(VSCode wrongly autocompleted some of my import statements in this manner)
Try exiting your current Terminal instance and running the app in a new instance
I made the silly mistake of naming my file secret.env because that's how I always did it in Node.js.
After changing the name to .env, restarting the terminal, and running npm start again, everything worked like a charm
I didn't get any value back as well. For some reason, I thought the environment file should be dev.env, qa.env etc. Actually, it's just ".env". That's that. In case some else makes this mistake.
create-react does not supports hot reload feature .env files since they are not Javascript. So, when you change the env files make sure to manually start your server to see the effect of new changes.
In my case, a manual restart of the server worked fine :)
What worked for me was to install env-cmd and after that in my package.JSON add the following line of code
"scripts": {
"start": "env-cmd -f .env.development react-scripts start ",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
}
As of latest react-scripts (3.2.0) it's a simple as putting say
PORT=4000
BROWSER=none
in your .env or .env.development file (..etc) which is supposed to be in the root folder.
It will NOT work with then REACT_APP prefix (the docs are outdated I guess) and it does NOT require any extra npm packages (react-scripts already includes dotenv 6.2.0)

Resources