If you're using Webpack in your Rails app there's a much easier solution.
TLDR: Use either process.env.RAILS_ENV or process.env.NODE_ENV
In one of your webpack-compiled javascript files:
console.log('Rails env: ', process.env.RAILS_ENV);
console.log('Node env: ', process.env.NODE_ENV);
Full solution you can copy-paste is below. Documentation for process.env.
As pointed out in u/matthew's answer, there are risks in using Rails.env in erb files. Similarly, if NODE_ENV is not configured properly on your production server, you may have unexpected or dangerous behaviour. I'd suggest implementing a small module that checks for both variables, and throws an error if they don't match.
Full Solution
- Implement a small module that checks both environments
- Import this module where needed
javascript/environment/index.js
/* global process */
const railsEnv = process.env.RAILS_ENV;
const nodeEnv = process.env.NODE_ENV;
if (!railsEnv || railsEnv !== nodeEnv) {
const errorMsg = `RAILS_ENV (${railsEnv}) does not match NODE_ENV (${nodeEnv})`;
throw new Error(errorMsg);
}
export default railsEnv;
Now use anywhere you'd like, such as in a React component.
javascript/components/MyComponent
import env from '../../environment';
class PaintTheKeyboard extends React.Component {
constructor(props) {
super(props);
console.log(env);
}
...
render() { ... }
}
Rails.envvariable is being outputted in the script? You may need to change the extension toapplication.js.erbto ensure it's parsed