How to Use Rails Backend with React Frontend
Rails is a great tool for writing an app from the bottom to the top. It’s MVC pattern is easy to grasp and can be very useful for separating the concerns. It has a lot of gems on top of each other to make the framework’s writing experience easier. Those gems and their duties is another topic, and I’ll write about them in another article. But when it comes to the frontend, I am not a big fan of the Rails. So today I’ll quickly demonstrate to you, how to configure rails backend with React frontend in two different ways. The first one is an API only option, and the second one is configuring a full rails app with react in it. Let’s start.
API ONLY OPTION
To have an API, without the views all you need to do is;
rails new <name_of_your_app> — database=postgresql — api -T
Let’s investigate the command above. The first part is similar to generate a regular rails app. The — database=postgresql changes our database configuration from SQLite to PostgreSQL. The — api flag signifies that it is an API only app. This configuration removes all assets related gems and adds a hint about the cors gem. It also skips the sessions and cookies support and if you need them, you need to enable it manually. I generally prefer a token-based approach during the last days, however, if you prefer a cookie-based authentication, I highly recommend this series to you, which uses Rails and React as well. However, I have to warn you, Heroku drops support for cookie authentication for non-customized domains. You can either buy a custom domain or just work locally, to make your session cookies work. To dive into the differences between API only option and the regular app. you can refer here. Let’s move on. The -T option skips the tests which we don’t need on our tutorial.
After those steps, I generally add a .env file to the root folder and add this file to .gitignore as well. In this .env file;
DB_USERNAME=<your_user_name>DB_PASSWORD=<your_password>
After this arrangement, I add rails dotenv to my gem file. Then in the config/database.yml, I am adding those lines to the necessary DB sections.
username: <%= ENV[‘DB_USERNAME’] %>password: <%= ENV[‘DB_PASSWORD’] %>
Note: If you haven’t installed PostgreSQL locally nor set-up a role, please refer here before generating the rails app.
Next, if you need authentication and encryption, you can uncomment rack-cors and bcyrpt. I’ll dive deep into the authentication process with Rails in another article.
Here all you need to create an endpoint and reference it from the frontend. For testing purposes, I’ll scaffold a User model.
rails g scaffold User
This command creates a migration, a controller layout, a model file for the User, and user resources in routes. In this demo, I’ve created an empty scaffold so you can configure it as per your needs.
Finally;
rails db:createrails db:migraterails s -p 3001
Those three commands set up your database and run your local server on port 3001.
Let’s move on to our Frontend
npx create-react-app <your_app_name>
This command will generate a scaffold react app with suggested dependencies.
Note: This command should be run from somewhere else, not inside the rails app’s directory.
After it’s finished you can configure your React app as per your needs. For example, if you’d like to use redux, just
yarn add redux react-redux
This command changes your package.json and adds necessary dependencies to your app. I’ll list some useful packages and continue with my tutorial.
yarn add axios bootstrap jquery popper.js
I’m keeping it simple. Right now to talk with the API and get some data or post some data all you need to do is;
axios.get(‘http://localhost:3001/users).then(response => console.log(response.data))
This command will get all the users from your API and if you need another endpoint, for example, adding a user all you need to do make a post request to the same endpoint. Right now I am just console logging the result but you can take the promise and resolve it as per your needs.
Configuring Rails with webpack=react
This option will create a react template on your app/javascript/packs folder. All you need to do connect this pack with your application_hmtl.rb template in the layout views, or another view that you want to display the frontend with.
rails new <your_app_name> -d=postgresql -T — webpack=react — skip-coffee
This command is generating a full rails app with webpack react configuration. -T is again skipping the tests and we are skipping coffee-script at this time as well.
Now please refer to the scaffolding the user model, database setup configurations above and run bundle install and finally,
rails s
To run your local server.
You should see the rails generic view when you open the localhost.
Now let’s connect our react view to our backend.
I’m assuming you’ve scaffolding the User so go to views/users/index.html.erb and put this line
<%= javascript_pack_tag ‘hello_react’ %>
After that go to your routes.rb in the config and change the root to this;
root ‘users#index’
When you refresh the page you’ll see Hello react on your screen. Now your frontend is connected with your backend. You can configure your routes, frontend and you can use this layout and add more components on top of it.
For a detailed tutorial, you can check this.
I’ve tried to make this as easy and beginner-friendly as I can. For more information, you can reach out to me via the links. There will be more on this topic, in the upcoming days. Thanks for reading!