React + Webpack: Where To Configure REST Endpoints
I have a React+Flux app and using Webpack. The REST API I am consuming is served by a different server and I am trying to figure out where I could specify the backend endpoint constant depending whether I am on dev or prod environments.
Currently, for dev, I have harcoded the URL to be localhost:port, but when I deploy, it still tries to access the endpoints at localhost.
It seems like it should be something pretty common, but can't find any info.
Answer
You can add environmental variables to your webpack scripts. A common practice for node is to use ENV=production||dev when you are using the webpack script in bash or your package.json. Next you can create two different config files, one for production and one for dev.
plugins: [
new webpack.DefinePlugin({
ENV: process.ENV === 'dev' ? require('./dev-config-path')) : require('./prod-config-path')
})
]
ENV should now be attached to the window object. Make sure not to add API keys or anything since it will be accessible. You could also just hardcode the api URL.
plugins: [
new webpack.DefinePlugin({
API: process.ENV === 'dev' ? 'localhost:3000' : 'xxx.xxx.x.x'
})
]
Related Questions
- → OctoberCMS Rain User plugin not working or redirecting
- → Good solution to work with rest-api like SPA with redux?
- → Transformer usage on laravel/dingo API
- → Ember.js JSON API confusion
- → Express - better pattern for passing data between middleware functions
- → Checking passed object existence in Laravel delayed queue job
- → Restrict .htm Pages and Partials in OctoberCMS with Nginx
- → Nested array validation laravel
- → Uploading a file and sending it to the backend with React and Node
- → Javascript onClick not firing when assigned inside of array.map
- → How to replace the 3rd product with an Image in product list for Perstashop?
- → How should I implement canonical urls in my prestashop theme?
- → Best way to do front-end public and restricted area with October CMS?