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

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.

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

Launch mock server on vercel

I have a React project and installed mock server with json-server node module.
(For your note: Here is the json-server documentation for better understanding. [link]1)
I can start mock server with npm script [npm run mock].
After run the script, mock server start working with this link: localhost:3000.
This react project is working well on local environment.
Now I am going to deploy react project on vercel.
But I have no idea for start mock server on vercel.
How can I start mock server on vercel?
Here is the scripts of package.json file for the application.
{
...
"scripts": {
"start": "PORT=3001 react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"mock": "json-server --watch src/mock/db.json",
"preinstall": "npm install --package-lock-only --ignore-scripts && npx npm-force-resolutions"
}
...
}
Please ask me more information what you want to check.
I had a similar issue and this article save my life.
https://shadowsmith.com/how-to-deploy-an-express-api-to-vercel
Instead of deploying together with my React project, I deploy JSON Server as a separate mock server.
First of all, you need to create a server.js to run JSON Server as a module.
Reference: https://github.com/typicode/json-server#module
At the end of the file, export server in order for Vercel to turn Express into a serverless function
// Export the Express API
module.exports = server;
Last but not least, create a vercel.json in order to deploy to Vercel.
Here are my scripts for your reference purpose: https://github.com/kitloong/json-server-vercel

Default port number will not change for my react app

Hi I am new to react and would like to change my react port number of 3000
as i have an express server running on the 3000.
So obviously i look through stackoverflow answers and i tried everything recommended.
i created a .env in root folder (public) and set the port to = 4000
tried the same in .env.development
i added:
"scripts": {
"start": "set PORT=3500 && react-scripts start",
"build": "react-scripts build"
}
in my json file.
but only to end up with below upon restart
Local: http://localhost:3000
On Your Network: http://192.168.2.19:3000
What could i possbily be missing in my app that its working for other ppl but not for me??
please let me know
If you're on Mac/Linux the start command is slightly different:
"start": "PORT=3500 react-scripts start"

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)

Passing Environment variables to React application from Package.json

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

Resources