Reputation: 3307
I'm working on a React web app which was created by create-react-app
and I am getting ready to deploy it.
The issue is, for development, the app uses the api instance running on my dev environment (localhost:{api-port}) but for the deployed app this should point to the server api instance (api.myapp.com).
Currently the host is just a variable in my networking component:
const hostname = 'localhost:9876'
I plan on using webpack to generate the static files which will be served by the production front-end, and I would like to continue developing using npm start
as set up by create-react-app
.
What would be the correct way to set up my project such that the host can be set automatically to the correct value based on whether I'm running the dev server or building for production?
Upvotes: 4
Views: 1237
Reputation: 3905
you could use a relative path when you make any request to your api server instead of calling the full url for your app.
and for your development you could add a proxy property to your package.json file:
{
...
"proxy": {
"/api/*": {
"target" :"http://localhost:9876"
}
}
}
so whenever you make any request that prefixed with /api
will be redirected to http://localhost:9876/api
this is just in the development but in the production if you make a request prefixed with /api
it won't be redirected it will be served normally because the proxy is just available in the dev server coming with create-react-app
.
Upvotes: 0
Reputation: 1671
A common solution is to check against process.env.NODE_ENV
like this:
const hostname = process.env.NODE_ENV === "development" ? "localhost:9876" : "localhost:6789";
You may need to force the environment variable to be present in your Webpack configuration file using the DefinePlugin
like this:
plugins: [
new webpack.DefinePlugin({
"process.env": {
NODE_ENV:JSON.stringify(process.env.NODE_ENV || "development")
}
})
]
An alternative solution might be to use the config package and provide your hostname string as a configuration parameter. config will inherit configurations from files based on the current NODE_ENV. It will start by using configuration from a default.json file, then override it with a development.json, or production.json, depending on your environment.
Note that you'll need for the config files to be copied to your output directory using CopyWebpackPlugin for it to work.
Upvotes: 2
Reputation: 427
There are definitely many ways you could achieve that. One of those solutions would be to use webpacks's DefinePlugin
. In your plugins section in webpack configuration you would add something like this:
new webpack.DefinePlugin({
API_HOST: process.env.NODE_ENV === 'production'
? JSON.stringify('localhost:8080')
: JSON.stringify('api.com')
}),
That creates a global variable API_HOST
available everywhere in your codebase, which you can use. You can read more about the DefinePlugin
here https://webpack.js.org/plugins/define-plugin/
Upvotes: 0