React_on_rails: Deploying to Heroku, how to reference environment variables

Created on 16 Oct 2016  路  4Comments  路  Source: shakacode/react_on_rails

My app refers to an api endpoint as such:

dispatch(setEndpointHost('https://staging.myapp.com'))

But I want this to adjust depending on domain.
Locally I want localhost:3000 and for production I want something else.

How can I refer to environment variables known to Heroku?
According to heroku I can just use:

process.env.ENVVARIABLENAME

ref: getting-started-with-nodejs#define-config-vars

So for example:

$> heroku config:set DOMAIN=localhost:3000

And then my react code reads:

dispatch(setEndpointHost(process.env.DOMAIN)

...but my app doesn't understand 'process'

What is the correct way to do this?

Most helpful comment

The process object is only accessible from Node, not from the the client side. If you to use it on the client side, you can add it to your webpack configuration like so:

config.plugins.push({
  new webpack.DefinePlugin({
    'process.env': {
       ENVVARIABLENAME: process.env.ENVVARIABLENAME
    }
  })
});

This should work since your webpack file runs on the server side, and should therefore have access to environment variables. I didn't test it or anything, though.

All 4 comments

The process object is only accessible from Node, not from the the client side. If you to use it on the client side, you can add it to your webpack configuration like so:

config.plugins.push({
  new webpack.DefinePlugin({
    'process.env': {
       ENVVARIABLENAME: process.env.ENVVARIABLENAME
    }
  })
});

This should work since your webpack file runs on the server side, and should therefore have access to environment variables. I didn't test it or anything, though.

Here's an example: https://github.com/shakacode/react-webpack-rails-tutorial/blob/master/client/webpack.client.base.config.js#L55

  plugins: [
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify(nodeEnv),
      },
      TRACE_TURBOLINKS: devBuild,
    }),

anyone know how to solve this issue using create-react-app. Im no react expert but Im told that when using create-react-app the previous said solution doesnt apply?

@ben-mvi you can use the JS client side code (not Webpack) from create-react-app. Use what you find in the default generator to inspire your Webpack config. Other places to look include the webpack configs found:

Was this page helpful?
0 / 5 - 0 ratings

Related issues

CodyFitzpatrick picture CodyFitzpatrick  路  6Comments

chintanparikh picture chintanparikh  路  5Comments

robwise picture robwise  路  3Comments

jtibbertsma picture jtibbertsma  路  7Comments

amf9t2 picture amf9t2  路  8Comments