Passing Environment variables to React application from Package.json - reactjs

following this article https://serverless-stack.com/chapters/environments-in-create-react-app.html
I am trying to add an environment variable to my react app which I have created using create react app. so my build command looks like below
"build": "REACT_APP_SECRET_CODE=123 react-scripts build",
while I try to run this build command in my Visual studio code terminal via
npm run build
it gives me the error that REACT_APP_SECRET_CODE is not recognized as an internal or external command.
How would i pass the environment variable in `package.json and build my app and access the variable value in my app.

If you don't want to install any other library. You can pass environment variable to yarn or npm command like this:
"scripts": {
"start": "breact-scripts start",
"start:env": "REACT_APP_ABC=xyz yarn start",
}
Note: Remember to put prefix "REACT_APP_" in your environment variable otherwise React won't allow it to use in app.

you can do it in a clean way (imo) using better-npm-run package
{
"devDependencies": {
"better-npm-run": "~0.0.1"
},
"scripts": {
"build": "better-npm-run build",
},
"betterScripts": {
"build": {
"command": "react-scripts build",
"env": {
"REACT_APP_SECRET_CODE": "123"
}
}
}
}
there are more advanced usage for this library, which I think might help you in the long term on your project

Related

How to rename 'index.js' file in React File structure to something else?

In the React file structure under components there is index.js file that runs the main character when running the project. Is there anyway to rename this file to any name I want? I am using PM2 server manager and there is no way for me to keep track which server is which when running multiple index.js files. So the only option I got is to rename this index.js to something specific to each project.
I have tried changing the package.json file's start script as below but nothing worked out only gave errors.
"scripts": {
"start": "test.js react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
}
Appreciate all your help!
You can't change the name of the file used by create-react-path.
You'll have to either eject to use custom webpack config by running
npm run eject
But it's a one-way operation (see documentation)
Or you can use Vite instead of create-react-app to bundle your project.
Vite is more configurable than create-react-app, you define in the index.html the name of your js file. So you can put any name you want.
Maybe even this example could help you:
https://vitejs.dev/guide/ssr.html#example-projects

Correct way to use scripts in react with .core

I am trying to figure out how to use the scripts inside package.json in my .core React project.
This is how it looks like:
"scripts": {
"start": "rimraf ./build && react-scripts start",
"build": "react-scripts build",
},
What if I want to add a custom script? For example, if I want to have a new script thats named "internal".
Whats the correct way to add this inside the script tag? And should I change something inside the .core Startup class? I mean how can the application know which Script to run if I don't define it somewhere?
Update: I have add the scripts from .core startup, but I am only getting interal server error (500) when trying this.
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseReactDevelopmentServer(npmScript: "start");
}
else if (env.IsStaging())
{
spa.UseReactDevelopmentServer(npmScript: "internal");
}
});
If you need more information. Please let me know.
Define your new script in the package.json:
"scripts": {
"start": "rimraf ./build && react-scripts start",
"build": "react-scripts build",
"internal": "(do something here)",
},
It looks like you're using ReactDevelopmentServerMiddlewareExtensions, so your spa.UseReactDevelopmentServer() takes a npmScript parameter that checks that package.json file and runs the command it finds there.
UPDATE:
Yes so your updated code looks like this is set up correctly on the .net end, you just need to write a corresponding script in package.json

How to access $PORT environment variable in React App on Heroku

I am running a server and a React site on the same Heroku app. My server.js is able to access the $PORT environment variable fine, but my React app is not getting anything from it (the variable is blank).
I need to be able to access the PORT environment variable because thats what my server (Radiks) is running on. From what I've read, React environment variables are only allowed if they are prefixed by REACT_APP_, so in the build script in package.json, I added a new environment variable that takes on the same values as $PORT.
My Procfile:
web: REACT_APP_PORT=$PORT node src/server.js
In package.json:
...
"scripts": {
"start": "node server.js",
"heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install && npm run build",
"build": "REACT_APP_PORT=$PORT react-scripts build",
"test": "react-scripts build",
"eject": "react-scripts eject",
"predeploy": "npm run build",
"deploy": "gh-pages -d build"
},
...
In my React app (App.js):
...
console.log("Connected to server:" + process.env.REACT_APP_PORT);
configure({ apiServer: process.env.REACT_APP_PORT || "http://localhost:1260", userSession})
...
(This ends up only printing out Connected to server:)
Any help would be greatly appreciated, thank you in advance!
From what I've read, React environment variables are only allowed if they are prefixed by REACT_APP_, so in the build script in package.json, I added a new environment variable that takes on the same values as $PORT.
That's new to me. I looked it up and also saw the passage that said this so I'm going to take your word for it.
web: REACT_APP_PORT=$PORT node src/server.js
Seems plausible.
"build": "REACT_APP_PORT=$PORT react-scripts build",
You are building your html, js, css files here. The port is never used. Heroku's $PORT value is dynamic. It changes from time to time. So when you are building your static files it still references a variable instead of a hardcoded value.
configure({ apiServer: process.env.REACT_APP_PORT || "http://localhost:1260", userSession}
Should be:
configure({ apiServer: "http://localhost:" + process.env.PORT || process.env.REACT_APP_PORT || 1260, userSession}
Just in case $PORT works I put it in there. If it does not exist it will pick $REACT_APP_PORT.
Your previous code was missing protocol and host.

Is there a way I can run next js application on https?

I have recently started working on nextjs framework and I have created an index.js document inside pages folder. I wanted to implement social login authentication and found for some reasons I need to run next js in https mode.
Can anybody tell me how can I do that in dev machine.
Here is my error message
error message
and here is my package.json scripts
"scripts": {
"dev": "next -p 3001",
"build": "next build",
"start": "next start",
},
This article on freeCodeCamp looks promising :
https://www.freecodecamp.org/news/how-to-get-https-working-on-your-local-development-environment-in-5-minutes-7af615770eec/

Not able to fetch .env urls to my component on my react project

I am using 3 .env file like .env.prod, .env.dev and .env. But not able to fetch the url to my component.
I am using react 16.9.
Can you please help me why I am not able to fetch it?
in my .env / .env.dev files
loginUrl = = "http://localhost:8080/api/2.0/admin/auth/login"
in my package.json files
"scripts": {
"start": "cp ./.env.dev .env && react-scripts start",
"build:dev": "cp ./.env.dev .env && react-scripts build",
"build:stage": "cp ./.env.stage .env && react-scripts build",
"build:prod": "cp ./.env.prod .env && react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},```
Inside my component, when I am printing it it is giving undefined.
console.log(process.env.loginUrl) is giving undefined
Using react-script
Looking at react script adding-custom-environment-variables documentation, variables are automatically loaded from .env if:
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.
Seams like the problem come from the name of your variable, try renaming in REACT_APP_LOGIN_URL
Note: this feature is available with react-scripts#0.5.0 and higher.
If using Webpack instead of react-script
You need to use webpack DefinePlugin to inject environments variables in your code.
In your webpack.config.js file :
require("dotenv").config(); // will load .env file in process.env
const webpack = require("webpack");
...
plugins: [
...
new webpack.DefinePlugin({
"process.env": {
NODE_ENV: JSON.stringify("production"),
SENTRY_DSN: JSON.stringify(process.env.SENTRY_DSN),
BUILD_DATE: JSON.stringify(new Date()),
TRAVIS_COMMIT: JSON.stringify(process.env.TRAVIS_COMMIT)
}
}),
...
]
Make sure you have strings only as if the value isn't a string, it will be stringified (including functions).
Then in your code, you can call console.log(process.env.NODE_ENV)

Resources