score:-1
you can define env variable for port and host.
react_app_port: "port of application",
react_app_host: "host of application"
to inject all the env to your application you can use webpack define plugin.
you need to add in plugins section like.
const env = require("path to your env file")
//other webpack settings
plugins: {
//plugins
new webpack.defineplugin(env)
}
now if you see the code of create-react-app it looks in env variable first to find the port
and host
.
also, note that
you must create custom environment variables beginning with
react_app_
. any other variables exceptnode_env
will be ignored to avoid accidentally exposing a private key on the machine that could have the same name
score:2
is it possible to set proxy settings in cra differently than with package.json?
no. it is not possible. well, at least not yet (2017/01/14).
the react proxy functionality is getting a bit complicated and as a result, the idea of setting up a proxy in a react app from env variables will be implemented as soon the simplification of the "advanced" proxy configuration is finished.
is this sentence about proxy or dev server itself?
it is about the dev server itself. all proxy configuration, as things stand, is configured in package file.
score:10
regarding:
use environment variables to inject the right server host and port into your app.
this refers to neither the proxy server nor the dev server. this is a recommendation on how to handle per-environment server settings if proxy
does not provide enough flexibility for you (i.e. if you need to use protocols other than http
, https
, or ws
). for example, if you have an api call within your code, you can use an environment variable to do something like this:
axios(process.env.react_app_base_url + endpoint, options).then(data=>{ console.dir(data); })
where each environment has it's own definition of react_app_base_url
.
without package.json
:
it is not possible to influence proxy settings without modifying package.json
.
see configuring the proxy manually (cra docs)
package.json
is the only documented way to influence proxy settings.
you can also see line 96 of cra's start.js
. this implementation leaves absolutely no ability to use env vars to inject the host/port to cra's proxy settings.
this is really one of the reasons i detest cra, to be honest. all of this behavior is so very easily handled when not bound by the limitations of cra.
you could just eject create react app:
npm run eject
all of these problems will go away instantly... the start.js
script referenced above is a bit of the code that is ejected. so you would very easily be able to replace those proxy settings with env vars.
just be certain to create a checkpoint for yourself prior to doing this as there is no reverting an ejection.
however--if you must stick with cra--you can very easily modify package.json
using environment variables.
how to inject env vars into package.json
at build time:
this is essentially what cra does with the react_app_
env vars (though it directly injects them into process.env
).
package.json
is just a big json object, so all you need to do is parse it on the server side right before you deploy, update the "proxy"
value to the ones provided by your env vars, save the file, and then run your build/deploy.
here is a very simple example of how to achieve this, you just need to run this script before deployment in a context where you still have access to process.env
:
const fs = require('fs');
// read/process package.json
const file = './package.json';
let pkg = json.parse(fs.readfilesync(file).tostring());
// at this point you should have access to your env vars
pkg.proxy = `${process.env.host}:${process.env.port}`;
// the 2 enables pretty-printing and defines the number of spaces to use
fs.writefilesync(pkg, json.stringify(file, null, 2));
i know this doesn't explicitly answer the question of how to handle this "without package.json", but i don't think that's the necessary approach anyways.
further, this does asnswer the title question of "how to inject port and host using env variable in create react app proxy settings?"
score:10
note: this feature is available with react-scripts@2.0.0 and higher.
you can manually configure proxy now. you need to install http-proxy-middleware
first.
npm install http-proxy-middleware --save
then create a file src/setupproxy.js
with following content.
const { createproxymiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(
'/api', // you can pass in an array too eg. ['/api', '/another/path']
createproxymiddleware({
target: process.env.react_app_proxy_host,
changeorigin: true,
})
);
};
you can add proxy now in the .env
file, remember you need the react_app_
prefix for development server to pick up the environment variable.
react_app_proxy_host=http://localhost:5000
ref: proxy manually
Source: stackoverflow.com
Related Query
- How to inject port and host using ENV variable in Create React App Proxy settings?
- How to create multiple page app using react
- How to create a preview (Image and description) to the Url when shared link on Social media,Gmail and Skype using React JS?
- How to analyze create react app build size and reduce it?
- How to read console.log from a mounted component with Enzyme and Jest in Create React App
- Custom Proxy in Create React App using Typescript
- How to avoid very long paths and use absolute paths within a Create React App project?
- Getting an out of memory error while using Create React App and Plotly.js
- How to build react app using Dockerfile.dev and Yarn
- React/webpack - How can I host react app on one server and images/fonts on another server?
- How to create and deploy a React App properly?
- How to create React App including Web3 using create-react-app? I am getting Module not found Error. BREAKING CHANGE: webpack < 5 used
- How to determine the order of css in my create react app build with webpack and customize-cra?
- How create a react app with a specific version using the npx command?
- How to create download feature using ASP.NET Core 2.1 and React JS?
- REACT: How to create a reusable custom hook with functions and effects that can change & react to changes in a host component's data
- ReactJS: How to inject component and pass variable in extended component instead using function
- How to point all node js microservices in single port locally and consume it in react app
- How to do gzip most efficiently in express react app made using nextjs framework and hosted on heroku
- how to communicate between a root React component and the rest of the app using Redux?
- How to create list and detail view using React Router DOM?
- How could I hide api key in my React app and host the working version in Github
- serve react create app and Nodejs app with reverse proxy Nginx
- How can I get rid of the `Node "13.0.0-nightly20190802452b393c1f"` so that I can be able to create a react app using the `create-react-app` tool?
- How to implement pagination in a Django and React app without using the REST framework?
- Create React App Build and Docker-Compose do not pass env variables
- How do I create an ag-Grid cell editor using React and TypeScript?
- How to make the filters work in this todo app created using react and redux?
- How to loop through an array an put create an array of objects using react and javascript?
- How to import image(SVG or PNG) in React using Create React App
More Query from same tag
- useHistory not defined in react custom Hook
- How remove or unmount React App from a website properly
- Upon clicking on links the view is unable to load?
- Overriding global type in typescript
- Why my central diagonal image's border is darker on the bottom edge?
- how to handle error in redux reducer
- How to save a list of json data that i get from an API to a class property using fetch
- Piping of RxJs Operators
- React: props.filter not working even though data is accessible
- React error on changing the inline-style of a component
- Delete file on realtime Database on Firebase with React.js
- styled-components - test createGlobalStyle
- Invariant Violation: Objects are not valid as a React child. Check the render method of `Content`
- Throttle is not working when using hooks setState
- how to pass initial state value using immutable js
- ReactJS with ReactRedux: Implementing Search to Query List of Items
- Redux Forms object in select
- React.js: How to show base64 image with ImageField of react-admin
- Passing components as state in React (Tab functionality)
- Can I use Firebase Analytics and gtag at the same time?
- Can’t read siteMetadata object from gatsby-config.js multiple queries GrahQL - Gatsby ReactJS
- Accessing Upload Data in React From Multer Node Server
- Create an array of object from given array key
- Material UI Data Grid Cell Edit revert commit
- How to clear react-select values on button click without adding it to options?
- React Change Image Source on Scroll Event
- reactjs dispatch promise continuously after specific time
- How I can make all my picture be on the same size
- Recursive function not working as expected when mapping through nested elements
- Logic for multiple phone number edit