Wednesday, February 3, 2021

Deployment

The following guide details how I deploy apps with a Rails backend and a React client side.

  1. We'll start with Rails, you'll need to have a Heroku account and the Heroku CLI installed

  2. Create a new Heroku project, this also adds a git remote to push to

    heroku create
    
  3. Make changes to your Rails code, commit and push to GitHub, ensure all the latest code changes are on your master branch, run this command:

    git push heroku master
    
  4. You'll need to format your production database with heroku run rails db:migrate, if you needed to seed your database in production it's heroku run rails db:seed

  5. Add a RAILS_MASTER_KEY to your Heroku ENV variables to ensure your production environment can decrypt your credentials file

  6. Moving back to the React client ensure you have a .env.production file in the root of your React project, it should look something like this:

    REACT_APP_BACKEND_URL=https://aqueous-badlands-44167.herokuapp.com
    
  7. Ensure your fetch requests are using the REACT_APP_BACKEND_URL variable correctly

    fetch(`${process.env.REACT_APP_BACKEND_URL}/your-endpoint`)
    
  8. Add a netlify.toml file to the root of your React project if you're using React Router

    [[redirects]]
      from = "/*"
      to = "/index.html"
      status = 200
    
  9. Sign up to Netlify

  10. Install the Netlify CLI, ensure that you run netlify login

  11. Add this script to your package.json

    "deploy": "yarn build && netlify deploy --prod --dir=build"
    
  12. Make changes to your React code, commit and push to GitHub, ensure all the latest code changes are on your master branch, run this command:

    yarn run deploy
    
  13. You'll get back a Netlify url that will be something like this:

    https://brave-curie-671954.netlify.app
    
  14. Add this url to your cors.rb file in your Rails project

    Rails.application.config.middleware.insert_before 0, Rack::Cors do
      allow do
        origins 'https://brave-curie-671954.netlify.app'
        resource '*', headers: :any, methods: [:get, :post, :put, :patch, :delete, :options, :head]
      end
    end
    
  15. Commit and push to GitHub, redeploy to Heroku

    git push heroku master