Rails

Integrate Rails with Strapi to build scalable, high-performance web applications, combining Rails’ robust business logic with Strapi’s flexible, headless content management

Rails logo

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.

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:

node -v
npm -v
ruby -v
rails -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:

STRAPI_API_URL=http://localhost:1337
STRAPI_API_TOKEN=your_strapi_token_here

For production, use Rails credentials:

EDITOR="vim" bin/rails credentials:edit

Add your Strapi configuration:

strapi:
  api_url: https://production-strapi-server.com
  api_token: your_secure_production_token

In your Strapi project, create a .env file with:

HOST=0.0.0.0
PORT=1337
APP_KEYS=change-me,another-key
API_TOKEN_SALT=random-salt
ADMIN_JWT_SECRET=another-random-secret
JWT_SECRET=random-jwt-secret
RAILS_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:

gem 'strapi_ruby'

Run bundle install, then create an initializer:

# config/initializers/strapi.rb
StrapiRuby.configure do |config|
  config.base_url = ENV['STRAPI_API_URL'] || Rails.application.credentials.dig(:strapi, :api_url)
  config.api_token = ENV['STRAPI_API_TOKEN'] || Rails.application.credentials.dig(:strapi, :api_token)
end

Now you can fetch content from Strapi in your Rails controllers:

class ArticlesController < ApplicationController
  def index
    @articles = StrapiRuby::Article.all
  end
end

Working with RESTful APIs

For direct API consumption from Rails, you can use the Net::HTTP library:

require 'net/http'
require 'json'

class StrapiService
  def self.fetch_articles(filters = {})
    uri = URI("#{ENV['STRAPI_API_URL']}/api/articles")
    uri.query = URI.encode_www_form(filters)

    req = Net::HTTP::Get.new(uri)
    req['Authorization'] = "Bearer #{ENV['STRAPI_API_TOKEN']}"

    res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http|
      http.request(req)
    end

    JSON.parse(res.body)['data']
  end
end

Use this service in your controller:

class ArticlesController < ApplicationController
  def index
    @articles = StrapiService.fetch_articles(sort: 'publishedAt:desc', pagination: { page: 1, pageSize: 10 })
  end
end

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:

gem 'graphql-client'

Set up the GraphQL client in an initializer:

# config/initializers/strapi_graphql.rb
require 'graphql/client'
require 'graphql/client/http'

module StrapiAPI
  HTTP = GraphQL::Client::HTTP.new("#{ENV['STRAPI_API_URL']}/graphql")
  Schema = GraphQL::Client.load_schema(HTTP)
  Client = GraphQL::Client.new(schema: Schema, execute: HTTP)
end

Create a query:

ArticlesQuery = StrapiAPI::Client.parse <<-GRAPHQL
  query($limit: Int) {
    articles(pagination: { limit: $limit }) {
      data {
        id
        attributes {
          title
          content
          publishedAt
        }
      }
    }
  }
GRAPHQL

Use the query in your controller:

class ArticlesController < ApplicationController
  def index
    result = StrapiAPI::Client.query(ArticlesQuery, variables: { limit: 10 })
    @articles = result.data.articles.data.map(&:attributes)
  end
end

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.

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:

# Gemfile
gem 'strapi_ruby'

# config/initializers/strapi.rb
StrapiRuby.configure do |config|
  config.base_url = ENV['STRAPI_API_URL']
  config.api_token = ENV['STRAPI_API_TOKEN']
end

Creating a service object for Strapi communication:

# app/services/strapi_service.rb
class StrapiService
  def self.fetch_articles(options = {})
    Rails.cache.fetch("strapi_articles_#{options.to_s.hash}", expires_in: 1.hour) do
      StrapiRuby::Article.all(options)
    end
  rescue => e
    Rails.logger.error("Strapi API error: #{e.message}")
    []
  end
end

Using the service in a controller:

class ArticlesController < ApplicationController
  def index
    @featured_articles = StrapiService.fetch_articles(
      filters: { featured: { eq: true } },
      sort: ['publishedAt:desc'],
      populate: ['image', 'author']
    )
  end
end

Handling paginated responses:

def fetch_paginated_content(page = 1, per_page = 10)
  StrapiService.fetch_articles(
    pagination: { page: page, pageSize: per_page }
  )
end

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.

Frequently Asked Questions

Ruby on Rails is a web application framework built on the MVC (Model-View-Controller) architecture. It provides a clean and efficient approach to building web applications. When integrated with Strapi, Rails handles the application logic, while Strapi acts as the headless CMS, providing a flexible, API-driven backend for content management.

Integrating Rails with Strapi offers a clear separation of concerns—Rails handles business logic, while Strapi manages content. This integration allows developers to focus on application features, while content creators can easily manage data through Strapi’s intuitive interface. It also enables the flexibility of headless CMS architecture, reducing dependency on front-end technologies.

To integrate Rails with Strapi, you need Ruby on Rails (version 7.x recommended), Node.js (version 14 or higher), npm (v6+), and a compatible database (PostgreSQL or MySQL). Additionally, you'll need basic knowledge of REST APIs and Rails development practices.

Set up Strapi by creating a new project with the command npx create-strapi-app@latest my-strapi-project. Create your content types in the Strapi admin panel, then configure your API endpoints and ensure the proper API permissions are set up to allow access from Rails. Configure your Strapi instance to use PostgreSQL or your preferred database.

In Rails, you can use the httparty or faraday gem to make HTTP requests to Strapi’s REST API. For example, you can create a simple service object to fetch content from Strapi, like this:

class StrapiService
  def self.fetch_articles
    response = HTTParty.get('http://localhost:1337/api/articles')
    JSON.parse(response.body)
  end
end
</details>