19

hello ive been trying to get the current environment in rails but i think im doing something wrong with my javascript, but i dont seem to know what. in my application.js i have...

var rails_env = '<%= Rails.env -%>';
alert(rails_env);
alert(rails_env.value);
if(rails_env == 'development'){
    alert('inside if')
    var indexName = "idx";
}
else{
    alert('inside else')
     var indexName = "idx_production";
}

it always goes into my else statement even if i am in development mode. what am i doing wrong? thank you

how to get environment in javascript file in rails app

3
  • 2
    Can you confirm that the Rails.env variable is being outputted in the script? You may need to change the extension to application.js.erb to ensure it's parsed Commented May 3, 2012 at 23:51
  • hmm on my first alert, itll say <%= Rails.env -%>. then on my 2nd its undefined. will changing it to application.js.erb mess up anything? like my pipeline? Commented May 3, 2012 at 23:55
  • You bet! I tied it up in an answer for google-security. Commented May 4, 2012 at 0:36

4 Answers 4

47

You dont need to pass it into your javascript file directly. You can do it in the erb view file like this for example:

<script>
  window._rails_env = "<%= Rails.env %>"
</script>

or better this:

<%= javascript_tag do %>
  window._rails_env = "<%= Rails.env %>"
<% end %>

or the best (IMHO) this:

<body data-env="<%= Rails.env %>">
  ...

and then:

var railsEnv = $('body').data('env')

Warning:

Dumping your entire Rails environment in script like this will almost certainly compromise your web app's security! As Michał Zalewski mentions in a comment below, your Rails application has sensitive information in its environment, like database credentials, API keys, application secrets for signing and encrypting cookies etc.

Sign up to request clarification or add additional context in comments.

1 Comment

Rails.env sometimes can contain confident information like database credentials.
17

Rails' asset pipeline will only preprocess assets that you mark for parsing. Whether those assets are going to end up CSS, JS, or whatever else, you can mark files for parsing by adjusting the file extension.

In this case, where you're trying to output an ERB variable, you will need to change the extension of the file to application.js.erb.

There's an extended discussion of the preprocessor here.

1 Comment

In my case I added an require path to a .js.erb file to the application.js file, then I am able to reference rails env variables like this: "<%= ENV["DESIRED_VAR"] %>" from within the .js.erb file
3

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() { ... }
}

Comments

2

For me, environment.js was located in /config/webpack/environment.js

2 Comments

how to create and use them? a example would be very helpful
@Prime I am not an expert with webpack, but I just tried rails new newapp and it comes with /config/webpack/environment.js file. (ralis version Rails 6.0.3.4)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.