Search code examples
restreactjswebpackfluxreactjs-flux

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.


Solution

  • 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'
        })
    ]