These integration guides are not official documentation and the Strapi Support Team will not provide assistance with them.
What Is Rails?
Ruby on Rails is a web application framework that streamlines development using the Model-View-Controller (MVC) architecture. Rails’ "convention over configuration" approach simplifies setup, allowing developers to focus on building unique features. This leads to faster development and more maintainable code.
Rails excels in rapid development with built-in generators and scaffolding, while its modular design ensures scalability. The Active Record ORM allows seamless database interaction. Rails has a strong community supporting the framework with gems and resources, and built-in testing tools promote test-driven development. Rails prioritizes developer experience without compromising quality or performance.
Why Integrate Rails with Strapi
Integrating Rails with Strapi creates a powerful tech stack where each platform excels in its area of expertise. Rails handles your core business logic, while Strapi provides flexible, headless content management through customizable APIs. By integrating the two, you can match Strapi’s content models with Rails data structures, allowing customized content types, fields, and relationships.
Strapi automatically generates RESTful and GraphQL APIs to enable Rails to consume content seamlessly without additional configuration. This API-first approach gives you flexibility in how content is fetched and displayed.
The separation between content management and application logic offers the benefits of a headless CMS. Content teams can work independently in Strapi’s intuitive interface, while developers focus on building features in Rails. Tools like the strapi_ruby gem make the integration feel native to Rails and streamline the process.
This architecture also improves performance. Delivering content through API calls reduces server load, and content-heavy applications scale more effectively. Using a CDN with Strapi further accelerates content delivery.
Strapi v5 includes enhanced GraphQL support, an improved plugin system, and optimized performance and caching. For security, built-in authentication, role-based access control, and JWT support ensure secure API communication.
Both platforms are open-source, so you can take advantage of community plugins, extensions, and resources. The integration also simplifies deployment, whether self-hosting or using Strapi Cloud, which allows you to focus on development.
Keep in touch with the latest Strapi and Rails updates
How to Integrate Rails with Strapi
Let's walk through how to integrate Rails with Strapi to create a robust foundation for content-rich web applications.
Prerequisites and Setup
Make sure you have these components installed:
- Node.js (v18 or v20 for Strapi v5)
- npm (v6+) or yarn
- Ruby (3.x recommended)
- Ruby on Rails (7.x recommended)
- PostgreSQL, MySQL, or another supported database
- HTTP client gem (httparty, faraday, etc.)
Check your installations with:
1node -v
2npm -v
3ruby -v
4rails -v
Strapi's documentation offers a compatibility table to check your version requirements.
Configuring Environment Variables
Secure communication between Rails and Strapi needs a proper environment variable setup.
For development, create a .env
file in your Rails project root:
1STRAPI_API_URL=http://localhost:1337
2STRAPI_API_TOKEN=your_strapi_token_here
For production, use Rails credentials:
1EDITOR="vim" bin/rails credentials:edit
Add your Strapi configuration:
1strapi:
2 api_url: https://production-strapi-server.com
3 api_token: your_secure_production_token
In your Strapi project, create a .env
file with:
1HOST=0.0.0.0
2PORT=1337
3APP_KEYS=change-me,another-key
4API_TOKEN_SALT=random-salt
5ADMIN_JWT_SECRET=another-random-secret
6JWT_SECRET=random-jwt-secret
7RAILS_ALLOWED_ORIGINS=http://localhost:3000,https://your-rails-app.com
Adjust these values for production, particularly the RAILS_ALLOWED_ORIGINS
.
Integrating Rails with Strapi using strapi_ruby Gem
Among the multiple Strapi integration methods, the strapi_ruby
gem makes integration straightforward. Add it to your Gemfile:
1gem 'strapi_ruby'
Run bundle install
, then create an initializer:
1# config/initializers/strapi.rb
2StrapiRuby.configure do |config|
3 config.base_url = ENV['STRAPI_API_URL'] || Rails.application.credentials.dig(:strapi, :api_url)
4 config.api_token = ENV['STRAPI_API_TOKEN'] || Rails.application.credentials.dig(:strapi, :api_token)
5end
Now you can fetch content from Strapi in your Rails controllers:
1class ArticlesController < ApplicationController
2 def index
3 @articles = StrapiRuby::Article.all
4 end
5end
Working with RESTful APIs
For direct API consumption from Rails, you can use the Net::HTTP
library:
1require 'net/http'
2require 'json'
3
4class StrapiService
5 def self.fetch_articles(filters = {})
6 uri = URI("#{ENV['STRAPI_API_URL']}/api/articles")
7 uri.query = URI.encode_www_form(filters)
8
9 req = Net::HTTP::Get.new(uri)
10 req['Authorization'] = "Bearer #{ENV['STRAPI_API_TOKEN']}"
11
12 res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http|
13 http.request(req)
14 end
15
16 JSON.parse(res.body)['data']
17 end
18end
Use this service in your controller:
1class ArticlesController < ApplicationController
2 def index
3 @articles = StrapiService.fetch_articles(sort: 'publishedAt:desc', pagination: { page: 1, pageSize: 10 })
4 end
5end
Understanding the differences between REST and GraphQL can help you choose the best approach for your application needs. Additionally, knowing how REST and GraphQL integration can work together may offer added flexibility.
Implementing GraphQL Queries
To use Strapi's GraphQL API, add the graphql-client
gem to your Gemfile:
1gem 'graphql-client'
Set up the GraphQL client in an initializer:
1# config/initializers/strapi_graphql.rb
2require 'graphql/client'
3require 'graphql/client/http'
4
5module StrapiAPI
6 HTTP = GraphQL::Client::HTTP.new("#{ENV['STRAPI_API_URL']}/graphql")
7 Schema = GraphQL::Client.load_schema(HTTP)
8 Client = GraphQL::Client.new(schema: Schema, execute: HTTP)
9end
Create a query:
1ArticlesQuery = StrapiAPI::Client.parse <<-GRAPHQL
2 query($limit: Int) {
3 articles(pagination: { limit: $limit }) {
4 data {
5 id
6 attributes {
7 title
8 content
9 publishedAt
10 }
11 }
12 }
13 }
14GRAPHQL
Use the query in your controller:
1class ArticlesController < ApplicationController
2 def index
3 result = StrapiAPI::Client.query(ArticlesQuery, variables: { limit: 10 })
4 @articles = result.data.articles.data.map(&:attributes)
5 end
6end
This approach gives you GraphQL's full power. For those interested in understanding GraphQL, it allows precise data fetching and reduces over-fetching, which is common with REST APIs.
Keep in touch with the latest Strapi and Rails updates
Project Example: Integrate Rails with Strapi (+ GitHub Repo)
Here are practical code examples for integrating Rails with Strapi:
Setting up the Strapi client in Rails:
1# Gemfile
2gem 'strapi_ruby'
3
4# config/initializers/strapi.rb
5StrapiRuby.configure do |config|
6 config.base_url = ENV['STRAPI_API_URL']
7 config.api_token = ENV['STRAPI_API_TOKEN']
8end
Creating a service object for Strapi communication:
1# app/services/strapi_service.rb
2class StrapiService
3 def self.fetch_articles(options = {})
4 Rails.cache.fetch("strapi_articles_#{options.to_s.hash}", expires_in: 1.hour) do
5 StrapiRuby::Article.all(options)
6 end
7 rescue => e
8 Rails.logger.error("Strapi API error: #{e.message}")
9 []
10 end
11end
Using the service in a controller:
1class ArticlesController < ApplicationController
2 def index
3 @featured_articles = StrapiService.fetch_articles(
4 filters: { featured: { eq: true } },
5 sort: ['publishedAt:desc'],
6 populate: ['image', 'author']
7 )
8 end
9end
Handling paginated responses:
1def fetch_paginated_content(page = 1, per_page = 10)
2 StrapiService.fetch_articles(
3 pagination: { page: page, pageSize: per_page }
4 )
5end
For more comprehensive examples and best practices, check out the strapi_ruby
GitHub repository, which provides a complete Ruby client for the Strapi API.
These patterns align with modern Jamstack features and can help you build scalable applications that combine Rails' robust back-end with Strapi's flexible content management. Remember to implement proper error handling, optimize queries for performance, and follow security best practices for API communication.
Strapi Open Office Hours
If you have any questions about Strapi 5 or just would like to stop by and say hi, you can join us at Strapi's Discord Open Office Hours, Monday through Friday, from 12:30 pm to 1:30 pm CST: Strapi Discord Open Office Hours.
For more details, visit the Strapi documentation and the Rails documentation.