Deploy Rails ActionCable to Heroku
If you built an app utilizing Rails ActionCable and you want to deploy it to Heroku, this short walkthrough is for you.
In the “Trailblaze” app I built with React/Rails, I implemented ActionCable in order to have a real-time chat feature. Getting the chat feature to work using WebSockets and ActionCable was somewhat difficult, but once I had it working in development there were some additional steps necessary to get the chat feature working in production. I was able to successfully deploy ActionCable to Heroku with the following steps:
Note: ActionCable subscribes and broadcasts from channels with Redis. Redis is an in-memory data structure used for data storage and caching in your app. Essentially, Redis keeps track of and syncs broadcasted content through ActionCable. Heroku requires a credit card on file but if you choose the nano version of Redis you won’t get charged but will be limited in data storage to 5MB.
- Create your Heroku app in the command line:
heroku create trailblaze-app
- Add the Redis To Go Addon.
heroku addons:add redistogo
- Now we will grab the Redis and utilize it in the backend.
heroku config --app trailblaze-app | grep REDISTOGO_URL
- You will be given a long url, such as:
redis://redistogo:c1e7c5c3ga5825b48375d058fj185or@spinfin.redistogo.com:9979/
- In your Rails app, make sure you are using the redis gem in your Gemfile:
gem ‘redis’
, then run:
bundle install - In your Rails app, open up
config/cable.yml
and enter your Redis url:production:
adapter: redis
url: redis://redistogo:c1e7c5c3ga5825b48375d058fj185or@
spinfin.redistogo.com:9979/ - In your
config/environments/production.rb
file, add the following:config.web_socket_server_url = “wss://trailblaze-app.herokuapp.com/api/v1/cable”
config.action_cable.allowed_request_origins = [‘https://trailblaze-app.netlify.app', ‘http://trailblaze-app.netlify.app']
Note: It's important that your request origins be your frontend. In this case, my frontend is in React and hosted on Netlify - Then push to Heroku in the command line:
If you are pushing from the root directory, use:git push heroku master
Or to push a subdirectory inside the root, use:git subtree push --prefix backend heroku master
- Migrate the database (CD into backend subdirectory if applicable):
heroku run rake db:migrate
- And finally, seed your data (CD into backend subdirectory if needed)
heroku run rake db:seed
That’s it!
Check out my Github to see what I’m up to:
https://github.com/dougschallmoser