I have deployed a mern stack application on heroku. Where the directory structure of my app is like this: -
|__client/ ** THIS IS EVERYTHING FROM THE REACT SIDE **
|__ node_modules/
|__ tons of stuff...
|__ public/
|__ index.html
|__ favicon.ico
|__ etc.
|__ src/
|__ index.js
|__ main/
|__ App.js
|__ etc.
|__ models/
|__ user.js
|__ todo.js
|__ etc.
|__ node_modules/
|__ stuff...
|__ routes
|__ userRoutes.js
|__ todoRoutes.js
|__ etc.
|__ .gitignore
|__ package.json
|__ server.js
|__ etc.
I have some environment variables set in heroku for backend that is working absolutely fine. I am serving my react build folder from the express app. My react app is having some env variables that I am not able to access. Is there any way I can access env in heroku from /client directory?
This is my package.json for backend
{
"name": "mern-to-heroku",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"dependencies": {
"body-parser": "^1.18.2",
"express": "^4.16.2",
"mongoose": "^4.13.6",
"morgan": "^1.9.0"
},
"scripts": {
"start": "node server.js",
"heroku-postbuild": "cd client && npm install --only=dev && npm install && npm run build"
},
"engines": {
"node": "8.9.2"
}
}
Env. are only available at build-time ( npm run build
) of your react app and will be then replaced with their value. They are not "available" at run-time of your application, so they can not be changed, after your react-app has been build.
That means you will have to build you app on heroku itself if the environment variables are only available on heroku.
Example: If you are using the deploy-to-heroku
button, you can add to app.json
(of course, needs to be customized for your setup):
"scripts": {
"postdeploy": "npm run build"
},
To build you react-app with the new env. after it has been deployed to heroku
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.