Prerequisites:
- Ruby 2.3+
- Rails 5.1+
- Webpacker 4.x.x
- Node.js 8.16.0+
- Yarn 1.x+
Add dotenv gem to your application's Gemfile:
gem 'dotenv-rails'
Create a file called ".env" in the root of your project. Next, set up your variables with the format key=value, delimited by line breaks:
API_KEY="YOURAPIKEYGOESHERE"
SECRET_KEY="YOURSECRETKEYGOESHERE"
Finally, make sure the .env file is not committed to your repository. This can be achieved by opening (or creating) a .gitignore file and adding this line:
.env # This contains secrets, don't store in source control
Head to your terminal to install dotenv with your preferred package manager:
npm i dotenv
yarn add dotenv
Add next lines to the "config/webpack/environment.js"
const { environment } = require('@rails/webpacker')
const webpack = require('webpack')
const dotenv = require('dotenv')
dotenv.config({ path: '.env', silent: true })
environment.plugins.prepend('Environment', new webpack.EnvironmentPlugin(JSON.parse(JSON.stringify(process.env))))
module.exports = environment
Done!
You can then reference these variables in your JavaScript app code with process.env
:
process.env.API_KEY // Compiles to "YOURAPIKEYGOESHERE"
in your Ruby code:
ENV['API_KEY'] # return "YOURAPIKEYGOESHERE"
Enjoy! :)