Create Task Manager app: Implement – Registration and Login APIs, Setup JSON Serializer

Let’s move to actual authentication APIs. We’ll implement Registration first, then Login. Keeping them separate will make it easier to understand password verification, JWT issuance and refresh-token management.

Step 4.3.1 – User Registration API

Our first endpoint, First authentication endpoint POST /api/v1/auth/register

1. Understand the registration flow

For this step, registration will create the User but won’t issue a JWT.

Why? We’ll implement login separately. Registration and authentication are different operations, even though some applications combine them.

2. Create the controller

Create these directories and file:

mkdir -p app/controllers/api/v1

touch app/controllers/api/v1/registrations_controller.rb

Controller: Api::V1::RegistrationsController

It should inherit from ApplicationController.

Implement one action: create

What should the action do?

A. Accept only permitted parameters

We should allow: email
password
password_confirmation

Never permit: password_digest
admin
role
account_status

The user must not be able to assign protected attributes through registration. Rails API applications include strong parameters and controller callbacks such as before_action through ActionController::API.

B. Create the user – Use the User model and handle validation failures.

C. Successful response – Return HTTP 201 Created.

Response contract:

{
  "user": {
    "id": 1,
    "email": "user@example.com"
  }
}

Important: Explicitly serialize only the allowed attributes. Don’t return user.as_json indiscriminately, because that could expose password_digest.

D. Failed response

Return HTTP 422 Unprocessable Entity.

Example:

{
  "errors": [
    "Email has already been taken"
  ]
}

Use the model’s validation errors rather than constructing your own validation logic in the controller.

3. Configure the API route

Open: backend/config/routes.rb

Add: POST /api/v1/auth/register

It should route to: Api::V1::RegistrationsController#create

Verify it: bin/rails routes

4. Write RSpec request specs

Create:

mkdir -p spec/requests/api/v1

touch spec/requests/api/v1/registrations_spec.rb

Use this structure:

RSpec.describe "API V1 Registration", type: :request do
  describe "POST /api/v1/auth/register" do
    # Examples
  end
end

Implement these five scenarios:

ScenarioExpected result
Valid registration201 Created
Duplicate email422 Unprocessable Entity
Missing email422 Unprocessable Entity
Missing password422 Unprocessable Entity
Malicious mass-assignment attributesProtected attributes ignored

Important security test

Imagine someone sends:

{
  "user": {
    "email": "attacker@example.com",
    "password": "password@1",
    "password_confirmation": "password@1",
    "password_digest": "attacker-controlled-value"
  }
}

Your controller must not permit password_digest. Verify that Rails generates the actual bcrypt digest from the submitted password instead. Also verify that the response does not contain password_digest. This is precisely the type of issue you might encounter in a Rails API controller security-review int.

5. Rate limiting – we’ll introduce it with Login

We’ll add rate limiting to the login endpoint because preventing password brute-force attempts is especially important.

Rails 8.1 provides:

rate_limit to: 10, within: 3.minutes, only: :create

By default, Rails scopes this limit by client IP and uses an ActiveSupport cache store. Exceeding the limit produces HTTP 429. We’ll also cover custom JSON responses for rate-limit failures.

6. Run and verify

Start Rails: bin/rails server -p 3000

You can manually test using curl:

curl -i -X POST http://localhost:3000/api/v1/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "user": {
      "email": "test@example.com",
      "password": "password@1",
      "password_confirmation": "password@1"
    }
  }'

Run RSpec:

bundle exec rspec spec/requests/api/v1/registrations_spec.rb

Step 4.3.2 – Login API

We’ll implement: POST /api/v1/auth/login

We’ll cover has_secure_password, authenticate, login rate limiting, refresh-token generation and cookie security.

Introducing JSON serializer: Blueprinter

I recommend using Blueprinter for our Rails API. It fits our application well, and I would introduce it now rather than building custom JSON serialization throughout our controllers.

We’ll also fix your registration implementation and request specs.

Blueprinter is a declarative JSON serialization library. It converts Ruby objects and ActiveRecord records into controlled JSON representations.
Github: https://github.com/procore-oss/blueprinter
Documentation: https://www.rubydoc.info/gems/blueprinter

Its main features are:

FeatureBenefit
Explicit fieldsControl exactly what the API exposes
ViewsDifferent response representations for different use cases
AssociationsSerialize related objects
Conditional fieldsInclude fields based on conditions
RenamingCustomize JSON attribute names
Collection renderingSerialize arrays and ActiveRecord relations

It also provides render_as_hash, which is useful when integrating with Rails controllers.

Is it actually fast?

Blueprinter is designed for performance, but I wouldn’t claim it is universally the fastest serializer.

For context, an older Rails 6.1/Ruby 2.7 benchmark found Blueprinter competitive with Alba and Panko, but the results depend on the workload and environment.

Three reasons to retaining Blueprinter for our project:

  1. Strong adoption relative to the alternatives.
  2. Explicit field definitions, views and association support.
  3. Enough flexibility for our User and Task API responses without introducing unnecessary complexity.

For our custom REST API, Blueprinter offers a good balance of readability, performance and maintainability.

Install Blueprinter

In backend/Gemfile, add: gem "blueprinter", "~> 1.3"

Then: cd backend
bundle install

The current RubyGems release listed is 1.3.0, and its declared minimum Ruby version is 3.1, so it meets our project’s declared Ruby requirement.

Create UserBlueprint

Create the directory and file:

mkdir -p app/blueprints

touch app/blueprints/user_blueprint.rb

Add:

class UserBlueprint < Blueprinter::Base
  identifier :id

  fields :email
end

Why only id and email?

Our User database record contains sensitive attributes. For example:

User
├── id
├── email
├── password_digest
├── created_at
└── updated_at

We only want:

{
  "id": 1,
  "email": "test@example.com"
}

This is an important security practice: explicitly whitelist fields for API serialization. Never serialize the entire ActiveRecord object. Blueprinter’s identifier and fields declarations give us control over exactly what is returned.

backend/app/controllers/api/v1/registrations_controller.rb:

class Api::V1::RegistrationsController < ApplicationController
  rate_limit to: 10, within: 3.minutes, only: :create

  def create
    user = User.new(registration_params)

    if user.save
      render json: UserBlueprint.render_as_hash(user, root: :data), status: :created
    else
      render json: { errors: user.errors.full_messages }, status: :unprocessable_entity
    end
  end

  private

  def registration_params
    params.require(:user).permit(:email, :password, :password_confirmation)
  end
end

Understand render_as_hash

Blueprinter offers different rendering methods:

MethodReturns
renderJSON string
render_as_hashRuby Hash
render_as_jsonJSONified Ruby Hash

We use: UserBlueprint.render_as_hash(user, root: :data)

This returns a Ruby Hash:

{
  data: {
    id: 1,
    email: "test@example.com"
  }
}

Rails then handles JSON encoding through: render json: ..., status: :created

One subtle but important point: avoid passing the JSON string returned by UserBlueprint.render into render json:. Rails could encode that string as another JSON string. render_as_hash avoids that issue.

Our API response contract

Successful registration – 201 Created

{
  "data": {
    "id": 1,
    "email": "test@example.com"
  }
}

Failed registration – 422 Unprocessable Entity

{
  "errors": [
    "Email has already been taken"
  ]
}

backend/spec/requests/api/v1/registrations_spec.rb:

require "rails_helper"

RSpec.describe "API V1 Registration", type: :request do
  let(:endpoint) { "/api/v1/auth/register" }

  let(:valid_params) do
    {
      user: {
        email: "test@example.com",
        password: "password@1",
        password_confirmation: "password@1"
      }
    }
  end

  describe "POST /api/v1/auth/register" do
    context "with valid attributes" do
      it "creates a user and returns 201 Created" do
        expect {
          post endpoint, params: valid_params, as: :json
        }.to change(User, :count).by(1)

        expect(response).to have_http_status(:created)

        user = User.find_by!(email: "test@example.com")

        expect(response.parsed_body).to eq(
          {
            "data" => {
              "id" => user.id,
              "email" => user.email
            }
          }
        )

        expect(user.authenticate("password@1")).to be_truthy
      end
    end

    context "with invalid attributes" do
      it "rejects duplicate email" do
        create(:user, email: "test@example.com")

        expect {
          post endpoint, params: valid_params, as: :json
        }.not_to change(User, :count)

        expect(response).to have_http_status(:unprocessable_entity)

        expect(response.parsed_body["errors"])
          .to include("Email has already been taken")
      end

      it "rejects email with different casing" do
        create(:user, email: "test@example.com")

        params = valid_params.deep_merge(
          user: { email: "TEST@EXAMPLE.COM" }
        )

        post endpoint, params: params, as: :json

        expect(response).to have_http_status(:unprocessable_entity)

        expect(response.parsed_body["errors"])
          .to include("Email has already been taken")
      end

      it "rejects missing email" do
        params = valid_params.deep_merge(
          user: { email: nil }
        )

        post endpoint, params: params, as: :json

        expect(response).to have_http_status(:unprocessable_entity)

        expect(response.parsed_body["errors"])
          .to include("Email can't be blank")
      end

      it "rejects missing password" do
        params = valid_params.deep_merge(
          user: {
            password: nil,
            password_confirmation: nil
          }
        )

        post endpoint, params: params, as: :json

        expect(response).to have_http_status(:unprocessable_entity)

        expect(response.parsed_body["errors"])
          .to include("Password can't be blank")
      end

      it "rejects password confirmation mismatch" do
        params = valid_params.deep_merge(
          user: { password_confirmation: "wrong-password" }
        )

        post endpoint, params: params, as: :json

        expect(response).to have_http_status(:unprocessable_entity)

        expect(response.parsed_body["errors"])
          .to include("Password confirmation doesn't match Password")
      end
    end

    context "with malicious mass-assignment attributes" do
      it "does not allow password_digest to be assigned" do
        attacker_digest = SecureRandom.hex(32)

        params = valid_params.deep_merge(
          user: { password_digest: attacker_digest }
        )

        post endpoint, params: params, as: :json

        expect(response).to have_http_status(:created)

        user = User.find_by!(email: "test@example.com")

        expect(user.password_digest).not_to eq(attacker_digest)
        expect(user.authenticate("password@1")).to be_truthy

        expect(response.parsed_body.dig("data").keys)
          .to contain_exactly("id", "email")
      end
    end
  end
end

Important testing concepts in this spec

1. change(User, :count).by(1) – This verifies the database side effect, not just the HTTP response.

2. as: :json – This tells Rails that we’re sending a JSON request. It also helps test the actual JSON API contract.

3. response.parsed_body – Avoid manually parsing JSON with JSON.parse(response.body) when Rails already provides this helper.

4. deep_merge – Preserves the nested user structure when overriding individual attributes.

5. contain_exactly – Verifies the serialized response contains exactly the permitted attributes, irrespective of ordering.

project structure

Our backend now has:

backend/
├── app/
│   ├── blueprints/
│   │   └── user_blueprint.rb
│   │
│   ├── controllers/
│   │   └── api/
│   │       └── v1/
│   │           └── registrations_controller.rb
│   │
│   └── models/
│       ├── user.rb
│       └── task.rb
│
├── config/
│   └── routes.rb
│
└── spec/
    └── requests/
        └── api/
            └── v1/
                └── registrations_spec.rb

Run: bundle exec rspec spec/requests/api/v1/registrations_spec.rb
Then: bundle exec rspec

API documentation – absolutely, we should have it

I strongly recommend documenting our API using the OpenAPI Specification

Why?

Imagine another developer joins your project. They shouldn’t need to read all your Rails controllers to understand the API. Documentation should tell them:

  • Available endpoints.
  • HTTP methods.
  • Required request parameters.
  • Request and response JSON structures.
  • Authentication requirements.
  • HTTP status codes.
  • Validation errors.
  • Pagination and filtering parameters.

A frontend developer can understand this without knowing anything about Rails.

OpenAPI is a machine-readable contract that describes these API operations, parameters, schemas, security requirements and responses.

Official standard: https://spec.openapis.org/oas/latest.html

rspec-openapi

Generates OpenAPI from existing RSpec request specs. Requires a separate documentation UI.

My recommendation: rspec-openapi + Swagger UI

rspec-openapi – 0.36.0 · November 1, 2026

It generates OpenAPI specifications directly from existing RSpec request specs without requiring a special testing DSL.

It has approximately 3.63 million RubyGems downloads and supports OpenAPI 3.0, 3.1 and 3.2. GitHub repository

Swagger UI – Documentation presentation

Displays the generated OpenAPI file as interactive documentation, including endpoint descriptions, parameters, schemas and request testing. Swagger UI website

How will this work?

For example, when we write:

describe "POST /api/v1/auth/register" do
  it "creates a user" do
    post "/api/v1/auth/register",
      params: valid_params,
      as: :json

    expect(response).to have_http_status(:created)
  end
end

We can run: OPENAPI=1 bundle exec rspec

The tool generates:

doc/
└── openapi.yaml

The generated specification can then be loaded by Swagger UI.

One useful feature is that rspec-openapi preserves manual modifications when updating generated documentation. This matters because generated schemas sometimes need human refinement.

Our final tooling decisions

Rails API tooling baseline

ConcernSelected tool
SerializationBlueprinter
API specificationOpenAPI 3.2
Documentation generationrspec-openapi
Documentation UISwagger UI
Backend testingRSpec
Test dataFactoryBot
AuthenticationJWT + opaque refresh token

When should we introduce API documentation?

I’d introduce rspec-openapi after completing our first few request specs. That way, we won’t create documentation for endpoints that are still changing.

Our learning sequence will now be:

  1. Complete registration API and its request specs.
  2. Implement login, JWT response and refresh-token cookie.
  3. Add authenticated Task CRUD endpoints.
  4. Introduce rspec-openapi and generate our first OpenAPI document.
  5. Configure Swagger UI.
  6. Update documentation whenever request contracts change.
  7. Add API documentation generation and validation to GitHub Actions CI.

This also gives us an excellent engineering practice: API tests become part of our API documentation workflow.

Step 4.3.2 – Login API

Authentication implementation

Our endpoint:

POST /api/v1/auth/login

1. Understand the login flow

For this milestone, we’ll generate only the JWT access token. The opaque refresh token and HttpOnly cookie will come next.

2. Create SessionsController

I recommend naming this controller SessionsController.

Why?

A session represents an authenticated user’s interaction with our application. Login, refresh and logout are all part of the session lifecycle.

Create: touch app/controllers/api/v1/sessions_controller.rb

Expected location: app/controllers/api/v1/sessions_controller.rb

Controller: Api::V1::SessionsController

Implement the create action.

A. Rate limiting

Use Rails’ built-in rate limiter:

rate_limit to: 10, within: 3.minutes, only: :create

Rails defaults to IP-based limiting and uses its configured ActiveSupport cache store. It returns HTTP 429 after the limit is exceeded.

For our API, customize the response to JSON:

{
"errors": ["Too many login attempts. Try again later."]
}

Use HTTP 429 Too Many Requests. We’ll later discuss per-account limits and distributed cache configuration for production.

B. Accept login parameters

We need only:

email
password

Create a private method named login_params. Use strong parameters.

Do not permit password_digest, admin, role or other protected attributes.

C. Find and authenticate the User

Use: User.find_by(...)

Then authenticate using: user.authenticate(...)

Remember how has_secure_password works:

  • Correct password returns the User object.
  • Incorrect password returns false.

Handle the case where the email doesn’t exist as well.

Important security requirement: Return exactly the same error message for an unknown email and an incorrect password.

For both: 401 Unauthorized

{
"errors": ["Invalid email or password"]
}

This prevents attackers from using the login endpoint to discover registered email addresses.

D. Generate JWT

Once credentials are valid: Authentication::AccessToken.issue(user)

E. Successful response

Use Blueprinter to serialize the User.

Our response contract:

{
  "data": {
    "access_token": "eyJhbGciOiJIUzI1NiJ9...",
    "token_type": "Bearer",
    "expires_in": 600,
    "user": {
      "id": 1,
      "email": "test@example.com"
    }
  }
}

Return HTTP 200 OK. Use the TTL constant from Authentication::Base instead of hardcoding 600.

Add the route

Open config/routes.rb. Add: post "auth/login", to: "sessions#create"

Inside our existing namespaces:

namespace :api do
  namespace :v1 do
    # Existing registration route
    # New login route
  end
end

Your RSpec request specs

Create: touch spec/requests/api/v1/sessions_spec.rb

Use:

RSpec.describe "API V1 Sessions", type: :request do
  describe "POST /api/v1/auth/login" do
    # Examples
  end
end

I want to cover these scenarios:

ScenarioExpected behaviour
Valid email and password200 OK
Incorrect password401
Non-existent email401
Missing email401
Missing password401
Invalid credentials responseSame generic error
Successful loginReturns valid JWT
JWT payloadCorrect User ID
Response serializationNo password_digest

Three important testing hints

1. Test the actual JWT

After logging in, extract: response.parsed_body.dig("data", "access_token")

Verify it using our existing: Authentication::TokenVerifier.verify(token)

Check that the returned sub matches the logged-in user’s ID.

2. Test security-sensitive response fields

Verify that the response doesn’t contain: password, password_digest

3. Test user enumeration protection

Make two login requests:

  • Existing email with incorrect password.
  • Non-existent email.

Verify both return the same HTTP status and error response. We want consistent external behaviour even though the internal failure reasons differ.

Manual API testing

Start Rails: rails server -p 3000

Try:

curl -i -X POST http://localhost:3000/api/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "login": {
      "email": "test@example.com",
      "password": "password@1"
    }
  }'

Make sure the email belongs to an existing user.

Run RSpec bundle exec rspec spec/requests/api/v1/sessions_spec.rb

Then: bundle exec rspec

I recommend normalizing the email before looking it up, because our User model normalizes emails to lowercase.

backend/app/controllers/api/v1/sessions_controller.rb:

class Api::V1::SessionsController < ApplicationController
  rate_limit to: 10,
             within: 3.minutes,
             only: :create,
             with: -> {
               render json: {
                 errors: ["Too many login attempts. Try again later."]
               }, status: :too_many_requests
             }

  def create
    email = login_params[:email].to_s.strip.downcase
    password = login_params[:password]
    user = User.find_by(email: email)

    unless password.present? && user&.authenticate(password)
      return render json: {
        errors: ["Invalid email or password"]
      }, status: :unauthorized
    end

    access_token = Authentication::AccessToken.issue(user)

    render json: SessionBlueprint.render_as_hash(
      user,
      root: :data,
      access_token: access_token,
      expires_in: Authentication::Base::ACCESS_TOKEN_TTL.to_i
    ), status: :ok
  end

  private

  def login_params
    params.require(:login).permit(:email, :password)
  end
end

Best way to create SessionBlueprint

I recommend a dedicated SessionBlueprint rather than putting login response construction inside the controller.

Why? A login response isn’t just a User. It includes authentication-specific information:

  • Access token.
  • Token type.
  • Expiration.
  • User information.

But we don’t need an ActiveRecord Session model just to serialize this response. Create: touch app/blueprints/session_blueprint.rb

backend/app/blueprints/session_blueprint.rb:

class SessionBlueprint < Blueprinter::Base
  field :access_token do |_user, options|
    options.fetch(:access_token)
  end

  field :token_type do |_user, _options|
    "Bearer"
  end

  field :expires_in do |_user, options|
    options.fetch(:expires_in)
  end

  association :user, blueprint: UserBlueprint do |user, _options|
    user
  end
end

Understand how this works

Notice:

field :access_token do |_user, options|
options.fetch(:access_token)
end

Blueprinter allows us to pass additional options while rendering.

For example:

SessionBlueprint.render_as_hash(
  user,
  root: :data,
  access_token: token,
  expires_in: 600
)

The user is the source object, while access_token and expires_in are additional rendering options. For the association:

association :user, blueprint: UserBlueprint do |user, _options|
  user
end

We reuse the existing UserBlueprint rather than duplicating the User serialization rules. This is supported by Blueprinter’s association and rendering-options APIs.

Our login response contract

Successful login – 200 OK

{
  "data": {
    "access_token": "eyJhbGciOiJIUzI1NiJ9...",
    "token_type": "Bearer",
    "expires_in": 600,
    "user": {
      "id": 1,
      "email": "test@example.com"
    }
  }
}

The JWT is returned to React. The password and password_digest are never serialized.

backend/spec/requests/api/v1/sessions_spec.rb:

require "rails_helper"

RSpec.describe "API V1 Sessions", type: :request do
  let(:endpoint) { "/api/v1/auth/login" }

  let(:user) do
    create(
      :user,
      email: "test@example.com",
      password: "password@1"
    )
  end

  let(:valid_params) do
    {
      login: {
        email: user.email,
        password: "password@1"
      }
    }
  end

  let(:invalid_response) do
    {
      "errors" => ["Invalid email or password"]
    }
  end

  describe "POST /api/v1/auth/login" do
    context "with valid credentials" do
      it "returns 200 OK" do
        post endpoint, params: valid_params, as: :json

        expect(response).to have_http_status(:ok)
      end

      it "returns an access token" do
        post endpoint, params: valid_params, as: :json

        body = response.parsed_body

        expect(body.dig("data", "access_token")).to be_present
        expect(body.dig("data", "token_type")).to eq("Bearer")
        expect(body.dig("data", "expires_in"))
          .to eq(Authentication::Base::ACCESS_TOKEN_TTL.to_i)
      end

      it "returns the authenticated user" do
        post endpoint, params: valid_params, as: :json

        expect(response.parsed_body.dig("data", "user")).to eq(
          {
            "id" => user.id,
            "email" => user.email
          }
        )
      end

      it "generates a valid JWT for the authenticated user" do
        post endpoint, params: valid_params, as: :json

        token = response.parsed_body.dig("data", "access_token")

        payload = Authentication::TokenVerifier.verify(token)

        expect(payload).to be_a(Hash)
        expect(payload["sub"]).to eq(user.id.to_s)
      end

      it "does not expose sensitive user attributes" do
        post endpoint, params: valid_params, as: :json

        body = response.parsed_body

        expect(body.dig("data", "user").keys)
          .to contain_exactly("id", "email")

        expect(body.to_json).not_to include("password_digest")
        expect(body.to_json).not_to include("password")
      end
    end

    context "with invalid credentials" do
      it "rejects an incorrect password" do
        params = valid_params.deep_merge(
          login: { password: "wrong-password" }
        )

        post endpoint, params: params, as: :json

        expect(response).to have_http_status(:unauthorized)
        expect(response.parsed_body).to eq(invalid_response)
      end

      it "rejects a non-existent email" do
        params = {
          login: {
            email: "unknown@example.com",
            password: "password@1"
          }
        }

        post endpoint, params: params, as: :json

        expect(response).to have_http_status(:unauthorized)
        expect(response.parsed_body).to eq(invalid_response)
      end

      it "rejects a missing email" do
        params = valid_params.deep_merge(
          login: { email: nil }
        )

        post endpoint, params: params, as: :json

        expect(response).to have_http_status(:unauthorized)
        expect(response.parsed_body).to eq(invalid_response)
      end

      it "rejects a missing password" do
        params = valid_params.deep_merge(
          login: { password: nil }
        )

        post endpoint, params: params, as: :json

        expect(response).to have_http_status(:unauthorized)
        expect(response.parsed_body).to eq(invalid_response)
      end

      it "uses the same response for unknown email and incorrect password" do
        invalid_password_params = valid_params.deep_merge(
          login: { password: "wrong-password" }
        )

        post endpoint, params: invalid_password_params, as: :json

        first_response = response.parsed_body

        post endpoint,
             params: {
               login: {
                 email: "unknown@example.com",
                 password: "password@1"
               }
             },
             as: :json

        second_response = response.parsed_body

        expect(first_response).to eq(second_response)
      end
    end

    context "with normalized email" do
      it "allows login using uppercase email" do
        params = valid_params.deep_merge(
          login: { email: "TEST@EXAMPLE.COM" }
        )

        post endpoint, params: params, as: :json

        expect(response).to have_http_status(:ok)
      end
    end
  end
end

Run: bundle exec rspec spec/requests/api/v1/sessions_spec.rb
Run every spec: bundle exec rspec spec/

What comes next: Refresh Token

Now we have: Completed design JWT generation, verification, registration and login. Our next small milestone is the refresh-token implementation.

We’ll introduce:

app/
├── models/
│   └── refresh_session.rb
│
└── services/
    └── authentication/
        └── refresh_token.rb

The flow will be:

We’ll learn refresh-token rotation, revocation, expiry, cookie configuration, CSRF and RSpec tests.

One architectural point: We won’t put the refresh token in the JSON response. It will be sent through an HttpOnly cookie, while the access JWT remains in React memory.

This keeps our authentication design consistent with the architecture we’ve chosen.

Check Refresh token here (Premium): https://railsdrop.com/create-task-manager-app-refresh-token-implementation/

4. Enable cookies in our API-only Rails application

This is an important configuration step.

Rails API-only applications exclude cookie middleware by default. We must explicitly add it and include the controller cookie module.

A. Update config/application.rb

Inside your Application configuration:

config.middleware.use ActionDispatch::Cookies

B. Update ApplicationController

backend/app/controllers/application_controller.rb:

class ApplicationController < ActionController::API
  include ActionController::Cookies
end

Now Rails controllers can read and write cookies.

C. Configure CORS for React

We’ll need this because:

React: http://localhost:5173
Rails: http://localhost:3000

These are different origins.

Add to your Gemfile:

gem "rack-cors"

Run:

bundle install

Create:

config/initializers/cors.rb

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins ENV.fetch("FRONTEND_ORIGIN", "http://localhost:5173")

    resource "/api/*",
      headers: :any,
      methods: %i[get post patch put delete options],
      credentials: true
  end
end

Important:

  • Never use origins "*" with credentialed requests.
  • credentials: true permits browser credential handling.
  • Use the exact frontend origin.

We’ll use credentials: "include" in React fetch calls later.

12. React integration – remember these requirements

When we build the React API service, the authentication requests must use:

fetch("http://localhost:3000/api/v1/auth/refresh", {
  method: "POST",
  credentials: "include",
});

credentials: "include" is essential because our refresh token is stored in a cookie and the frontend and backend have different origins.

The same option is required for login and logout so the browser can store and send the refresh cookie.

For ordinary task requests, we’ll send:

Authorization: Bearer <access_token>

We’ll keep the access token in React memory, not localStorage.

One security limitation: Logging out revokes the refresh-token family, but an already-issued access JWT remains valid until its 10-minute expiry. Immediate access-token revocation would require additional server-side state, such as a jti denylist or token-version check. We’ll discuss that when implementing authorization.

13. Next: Final backend milestone, then React

Step 4.5 – Protect Task APIs with JWT

We’ll implement only the essentials:

  1. authenticate_request! in ApplicationController.
  2. Extract the Bearer token.
  3. Call TokenVerifier.
  4. Find and set current_user.
  5. Protect Task endpoints.
  6. Scope every query through current_user.tasks.
  7. Add request specs for unauthorized access and cross-user task access.

Then start React

We’ll move to the frontend immediately after this:

  • React application structure.
  • Fluent UI layout.
  • Login and registration.
  • JWT integration.
  • Task list and task details.
  • React hooks, data fetching and caching.

I have deliberately kept the refresh-token implementation complete (even though I can’t work on it completely) but focused. Once the backend security boundary is in place, we can spend most of our remaining learning time on React, Docker and GitHub Actions.

Guide: Integrating React.js ⚛️ into a Rails 8 Application | Node.js | ESBuild | Virtual DOM- Part 1

1. Introduction and Motivation

Why React?

  • Declarative UI: build complex interfaces by composing small, reusable components.
  • Virtual DOM: efficient updates, smoother user experience.
  • Rich ecosystem: hooks, context, testing tools, and libraries like Redux.
  • Easy to learn once you grasp JSX and component lifecycle.

Why use React in Rails?

  • Leverage Rails’ backend power (ActiveRecord, routing, authentication) with React’s frontend flexibility.
  • Build single-page-app-like interactions within a Rails monolith or progressively enhance ERB views.

2. Prerequisites

  • Ruby 3.4.x installed (recommend using rbenv or RVM or Mise).
  • Rails 8.x (we’ll install below).
  • Node.js (>= 16) and npm or Yarn.
  • Code editor (VS Code, RubyMine, etc.).

Why Node.js is Required for React

React’s ecosystem relies on a JavaScript runtime and package manager:

  • Build tools (ESBuild, Webpack, Babel) run as Node.js scripts to transpile JSX/ES6 and bundle assets.
  • npm/Yarn fetch and manage React and its dependencies from the npm registry.
  • Script execution: Rails generators and custom npm scripts (e.g. rails javascript:install:react, npm run build) need Node.js to execute.

Without Node.js, you cannot install packages or run the build pipeline necessary to compile and serve React components.

What is Node.js?

Node.js is an open-source, cross-platform JavaScript runtime built on Chrome’s V8 engine. It enables JavaScript to be executed on the server (outside the browser) and provides:

  • Server-side scripting: build web servers, APIs, and backend services entirely in JavaScript.
  • Command-line tools: run scripts for tasks like building, testing, or deploying applications.
  • npm ecosystem: access to hundreds of thousands of packages for virtually any functionality, from utility libraries to full frameworks.
  • Event-driven, non-blocking I/O: efficient handling of concurrent operations, making it suitable for real-time applications.

Node.js is the backbone that powers React’s tooling, package management, and build processes.

3. Installing Ruby 3.4 and Rails 8

1. Install Ruby 3.4.0 (example using rbenv):

# install rbenv and ruby-build if not yet installed
brew install rbenv ruby-build
rbenv install 3.4.0
rbenv global 3.4.0
ruby -v   # => ruby 3.4.0p0

Check the post for using Mise as version manager: https://railsdrop.com/2025/02/11/installing-and-setup-ruby-3-rails-8-vscode-ide-on-macos-in-2025/

2. Install Rails 8:

gem install rails -v "~> 8.0"
rails -v   # => Rails 8.0.x

4. Generating a New Rails 8 App

We’ll scaffold a fresh project using ESBuild for JavaScript bundling, which integrates seamlessly with React.

rails new design_studio_react \
  --database=postgresql \
  -j esbuild
cd design_studio_react
  • --database=postgresql: sets PostgreSQL as the database adapter.
  • -j esbuild: configures ESBuild for JS bundling (preferred for React in Rails 8).

4.1 About ESBuild

ESBuild is a next-generation JavaScript bundler and minifier written in Go. Rails 8 adopted ESBuild by default for JavaScript bundling due to its remarkable speed and modern feature set:

  • Blazing-fast builds: ESBuild performs parallel compilation and leverages Go’s concurrency, often completing bundling in milliseconds even for large codebases.
  • Built‑in transpilation: it supports JSX and TypeScript out of the box, so you don’t need separate tools like Babel unless you have highly custom transforms.
  • Tree shaking: ESBuild analyzes import/export usage to eliminate dead code, producing smaller bundles.
  • Plugin system: you can extend ESBuild with plugins for asset handling, CSS bundling, or custom file types.
  • Simplicity: configuration is minimal—Rails’ -j esbuild flag generates sensible defaults, and you can tweak options in package.json or a separate esbuild.config.js.

How Rails Integrates ESBuild

When you run:

rails new design_studio_react --database=postgresql -j esbuild

Rails will:

1. Install the esbuild npm package alongside react dependencies.

2. Generate build scripts in package.json, e.g.:

"scripts": { 
"build": "esbuild app/javascript/*.* --bundle --sourcemap --outdir=app/assets/builds", 
"build:watch": "esbuild app/javascript/*.* --bundle --sourcemap --watch --outdir=app/assets/builds" 
}

3. Add a default app/assets/builds output directory and ensure Rails’ asset pipeline picks up the compiled files.

Customizing ESBuild

If you need to tweak ESBuild settings:

Add an esbuild.config.js at your project root:

const esbuild = require('esbuild')

esbuild.build({
  entryPoints: ['app/javascript/application.js'],
  bundle: true,
  sourcemap: true,
  outdir: 'app/assets/builds',
  loader: { '.js': 'jsx', '.png': 'file' },
  define: { 'process.env.NODE_ENV': '"production"' },
}).catch(() => process.exit(1))

Update package.json scripts to use this config:

"scripts": {
  "build": "node esbuild.config.js",
  "build:watch": "node esbuild.config.js --watch"
}

Why ESBuild Matters for React in Rails

  • Developer experience: near-instant rebuilds let you see JSX changes live without delay.
  • Production readiness: built‑in minification and tree shaking keep your asset sizes small.
  • Future-proof: the plugin ecosystem grows, and Rails can adopt newer bundlers (like SWC or Vite) with a similar pattern.

With ESBuild, your React components compile quickly, your development loop tightens, and your production assets stay optimized—making it the perfect companion for a modern Rails 8 + React stack.

5. What is Virtual DOM

The Virtual DOM is one of React’s most important concepts. Let me explain it clearly with examples.

🎯 What is the Virtual DOM?

The Virtual DOM is a JavaScript representation (copy) of the actual DOM that React keeps in memory. It’s a lightweight JavaScript object that describes what the UI should look like.

📚 Real DOM vs Virtual DOM

Real DOM (What the browser uses):
<!-- This is the actual DOM in the browser -->
<div id="todo-app">
  <h1>My Todo List</h1>
  <ul>
    <li>React List</li>
    <li>Build a todo app</li>
  </ul>
</div>
Virtual DOM (React’s JavaScript representation):
// This is React's Virtual DOM representation
{
  type: 'div',
  props: {
    id: 'todo-app',
    children: [
      {
        type: 'h1',
        props: {
          children: 'My Todo List'
        }
      },
      {
        type: 'ul',
        props: {
          children: [
            {
              type: 'li',
              props: {
                children: 'React List'
              }
            },
            {
              type: 'li',
              props: {
                children: 'Build a todo app'
              }
            }
          ]
        }
      }
    ]
  }
}

🔄 How Virtual DOM Works – The Process

Step 1: Initial Render
// Your JSX
const App = () => {
  return (
    <div>
      <h1>My Todo List</h1>
      <ul>
        <li>React List</li>
      </ul>
    </div>
  );
};
// React creates Virtual DOM
const virtualDOM = {
  type: 'div',
  props: {
    children: [
      { type: 'h1', props: { children: 'My Todo List' } },
      { 
        type: 'ul', 
        props: { 
          children: [
            { type: 'li', props: { children: 'React List' } }
          ]
        }
      }
    ]
  }
};
Step 2: State Changes
// When you add a new todo
const App = () => {
  const [todos, setTodos] = useState(['React List']);

  const addTodo = () => {
    setTodos(['React List', 'Build Todo App']); // State change!
  };

  return (
    <div>
      <h1>My Todo List</h1>
      <ul>
        {todos.map(todo => <li key={todo}>{todo}</li>)}
      </ul>
      <button onClick={addTodo}>Add Todo</button>
    </div>
  );
};
Step 3: New Virtual DOM is Created
// React creates NEW Virtual DOM
const newVirtualDOM = {
  type: 'div',
  props: {
    children: [
      { type: 'h1', props: { children: 'My Todo List' } },
      { 
        type: 'ul', 
        props: { 
          children: [
            { type: 'li', props: { children: 'React List' } },
            { type: 'li', props: { children: 'Build Todo App' } } // NEW!
          ]
        }
      },
      { type: 'button', props: { children: 'Add Todo' } }
    ]
  }
};
Step 4: Diffing Algorithm
// React compares old vs new Virtual DOM
const differences = [
  {
    type: 'ADD',
    location: 'ul.children',
    element: { type: 'li', props: { children: 'Build Todo App' } }
  }
];
Step 5: Reconciliation (Updating Real DOM)
// React updates ONLY what changed in the real DOM
const ul = document.querySelector('ul');
const newLi = document.createElement('li');
newLi.textContent = 'Build Todo App';
ul.appendChild(newLi); // Only this line runs!

🚀 Why Virtual DOM is Fast

Without Virtual DOM (Traditional approach):
// Traditional DOM manipulation
function updateTodoList(todos) {
  const ul = document.querySelector('ul');
  ul.innerHTML = ''; // Clear everything!

  todos.forEach(todo => {
    const li = document.createElement('li');
    li.textContent = todo;
    ul.appendChild(li); // Recreate everything!
  });
}
With Virtual DOM (React approach):
// React's approach
function updateTodoList(oldTodos, newTodos) {
  const differences = findDifferences(oldTodos, newTodos);

  differences.forEach(diff => {
    if (diff.type === 'ADD') {
      // Only add the new item
      const li = document.createElement('li');
      li.textContent = diff.todo;
      ul.appendChild(li);
    }
  });
}

🎭 Real Example with Our Todo App

Let’s trace through what happens when you add a todo:

Before Adding Todo:
// Current state
const [todos, setTodos] = useState([
  { id: 1, text: 'React List', completed: false },
  { id: 2, text: 'Build Todo App', completed: false }
]);

// Virtual DOM representation
{
  type: 'ul',
  props: {
    children: [
      { type: 'li', key: 1, props: { children: 'React List ⏳' } },
      { type: 'li', key: 2, props: { children: 'Build Todo App ⏳' } }
    ]
  }
}
After Adding Todo:
// New state
const [todos, setTodos] = useState([
  { id: 1, text: 'React List', completed: false },
  { id: 2, text: 'Build Todo App', completed: false },
  { id: 3, text: 'Master React Hooks', completed: false } // NEW!
]);

// New Virtual DOM
{
  type: 'ul',
  props: {
    children: [
      { type: 'li', key: 1, props: { children: 'React List ⏳' } },
      { type: 'li', key: 2, props: { children: 'Build Todo App ⏳' } },
      { type: 'li', key: 3, props: { children: 'Master React Hooks ⏳' } } // NEW!
    ]
  }
}
React’s Diffing Process:
// React compares and finds:
const changes = [
  {
    type: 'INSERT',
    location: 'ul',
    element: { type: 'li', key: 3, props: { children: 'Master React Hooks ⏳' } }
  }
];

// React updates ONLY what changed:
const ul = document.querySelector('ul');
const newLi = document.createElement('li');
newLi.textContent = 'Master React Hooks ⏳';
ul.appendChild(newLi); // Only this operation!

🎯 Key Benefits of Virtual DOM

1. Performance:
// Without Virtual DOM: Updates entire list
document.querySelector('ul').innerHTML = generateEntireList(todos);

// With Virtual DOM: Updates only what changed
document.querySelector('ul').appendChild(newTodoElement);
2. Predictability:
// You write declarative code
const TodoList = ({ todos }) => (
  <ul>
    {todos.map(todo => <li key={todo.id}>{todo.text}</li>)}
  </ul>
);

// React handles the imperative updates
// You don't need to manually add/remove DOM elements
3. Batching:
// Multiple state updates in one event
const handleButtonClick = () => {
  setTodos([...todos, newTodo]);     // Change 1
  setInputValue('');                 // Change 2
  setCount(count + 1);              // Change 3
};

// React batches these into one DOM update!

🔧 Virtual DOM in Action – Debug Example

You can actually see the Virtual DOM in action:

import React, { useState } from 'react';

const App = () => {
  const [todos, setTodos] = useState(['React List']);

  const addTodo = () => {
    console.log('Before update:', todos);
    setTodos([...todos, 'New Todo']);
    console.log('After update:', todos); // Still old value!
  };

  console.log('Rendering with todos:', todos);

  return (
    <div>
      <ul>
        {todos.map((todo, index) => (
          <li key={index}>{todo}</li>
        ))}
      </ul>
      <button onClick={addTodo}>Add Todo</button>
    </div>
  );
};

🎭 Common Misconceptions

❌ “Virtual DOM is always faster”
// For simple apps, Virtual DOM has overhead
// Direct DOM manipulation can be faster for simple operations
document.getElementById('counter').textContent = count;
❌ “Virtual DOM prevents all DOM operations”
// React still manipulates the real DOM
// Virtual DOM just makes it smarter about WHEN and HOW
✅ “Virtual DOM optimizes complex updates”
// When you have many components and complex state changes
// Virtual DOM's diffing algorithm is much more efficient

🧠 Does React show Virtual DOM to the user?

No. The user only ever sees the real DOM.
The Virtual DOM (VDOM) is never shown directly. It’s just an internal tool used by React to optimize how and when the real DOM gets updated.

🧩 What is Virtual DOM exactly?

  • A JavaScript-based, lightweight copy of the real DOM.
  • Stored in memory.
  • React uses it to figure out what changed after state/props updates.

👀 What the user sees:

  • The real, visible HTML rendered to the browser — built from React components.
  • This is called the Real DOM.

🔁 So why use Virtual DOM at all?

✅ Because manipulating the real DOM is slow.

React uses VDOM to:

  1. Build a new virtual DOM after every change.
  2. Compare (diff) it with the previous one.
  3. Figure out the minimum real DOM updates required.
  4. Apply only those changes to the real DOM.

This process is called reconciliation.

🖼️ Visual Analogy

Imagine the Virtual DOM as a sketchpad.
React draws the new state on it, compares it with the old sketch, and only updates what actually changed in the real-world display (real DOM).

✅ TL;DR

QuestionAnswer
Does React show the virtual DOM to user?❌ No. Only the real DOM is ever visible to the user.
What is virtual DOM used for?🧠 It’s used internally to calculate DOM changes efficiently.
Is real DOM updated directly?✅ Yes, but only the minimal parts React determines from the VDOM diff.

🧪 Example Scenario

👤 The user is viewing a React app with a list of items and a button:

<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  ...
  <li>Item 10</li>
</ul>
<button>Read More</button>

When the user clicks “Read More”, the app adds 10 more items to the list.

🧠 Step-by-Step: What Happens Behind the Scenes

✅ 1. User Clicks “Read More” Button

<button onClick={loadMore}>Read More</button>

This triggers a React state update, e.g.:

function loadMore() {
  setItems([...items, ...next10Items]); // updates state
}

🔁 State change → React starts re-rendering

📦 2. React Creates a New Virtual DOM

  • React re-runs the component’s render function.
  • This generates a new Virtual DOM tree (just a JavaScript object structure).

Example of the new VDOM:

{
  type: "ul",
  children: [
    { type: "li", content: "Item 1" },
    ...
    { type: "li", content: "Item 20" } // 10 new items
  ]
}

🧮 3. React Diffs New Virtual DOM with Old One

  • Compares previous VDOM (10 <li> items) vs new VDOM (20 <li> items).
  • Finds that 10 new <li> nodes were added.

This is called the reconciliation process.

⚙️ 4. React Updates the Real DOM

  • React tells the browser:
    “Please insert 10 new <li> elements inside the <ul>.”

✅ Only these 10 DOM operations happen.
❌ React does not recreate the entire <ul> or all 20 items.

🖼️ What the User Sees

On the screen (the real DOM):

<ul>
  <li>Item 1</li>
  ...
  <li>Item 20</li>
</ul>

The user never sees the Virtual DOM — they only see the real DOM updates that React decides are necessary.

🧠 Summary: Virtual DOM vs Real DOM

StepVirtual DOMReal DOM
Before click10 <li> nodes in memory10 items visible on screen
On clickNew VDOM generated with 20 <li> nodesReact calculates changes
DiffCompares new vs old VDOMDetermines: “Add 10 items”
CommitNo UI shown from VDOMOnly those 10 new items added to browser DOM

✅ Key Point

🧠 The Virtual DOM is a tool for React, not something the user sees.
👁️ The user only sees the final, optimized changes in the real DOM.


🎯 Summary

Virtual DOM is React’s:

  1. JavaScript representation of the real DOM
  2. Diffing algorithm that compares old vs new Virtual DOM
  3. Reconciliation process that updates only what changed
  4. Performance optimization for complex applications
  5. Abstraction layer that lets you write declarative code

Think of it as React’s smart assistant that:

  • Remembers what your UI looked like before
  • Compares it with what it should look like now
  • Makes only the necessary changes to the real DOM

This is why you can write simple, declarative code like {todos.map(todo => <li>{todo}</li>)} and React handles all the complex DOM updates efficiently!


🔄 After the Virtual DOM Diff, How React Updates the Real DOM

🧠 Step-by-Step:

  1. React creates a diff between the new and previous virtual DOM trees.
  2. React then creates a list of “instructions” called the update queue.
    • Examples:
      • “Insert <li>Item 11</li> at position 10″
      • “Remove <div> at index 3″
      • “Change text of button to ‘Read Less'”
  3. These changes are passed to React’s reconciliation engine.
  4. React uses the browser’s DOM APIs (document.createElement, appendChild, removeChild, etc.) to apply only the minimal changes.

✅ So instead of doing:

document.body.innerHTML = newHTML; // inefficient, replaces all

React does:

const newEl = document.createElement("li");
newEl.textContent = "Item 11";
ul.appendChild(newEl); // just this

❓ Why Didn’t Browsers Do This Earlier?

Excellent historical question. The short answer is: Browsers give us the tools, but React gave us the strategy.

⚠️ Why browsers didn’t do it automatically:

ReasonExplanation
🧱 Low-level APIsThe browser exposes DOM APIs (appendChild, setAttribute), but they’re imperative — devs must write the logic.
🤯 ComplexityManaging DOM efficiently across many updates (nested, reordered, conditional elements) is hard and bug-prone manually.
🔁 Manual state syncingBefore React, developers had to manually keep UI in sync with state. That logic got complex and messy fast.
📦 No built-in abstractionBrowsers don’t offer a built-in “virtual diff engine” or abstraction like React’s VDOM.

🤖 What React Added That Browsers Don’t

FeatureBrowser DOMReact (with VDOM)
Efficient diffing❌ No✅ Yes (reconciliation)
Declarative UI❌ No✅ Yes (return <UI />)
Component abstraction❌ No✅ Yes (function/class components)
State-driven rendering❌ Manual✅ Built-in
Minimal updates❌ Up to you✅ Automatic via VDOM

✅ TL;DR

  • React calculates exactly what changed via the virtual DOM diffing.
  • It then uses native DOM APIs to update only what’s necessary in the real DOM.
  • Browsers give you low-level control, but not an optimized strategy for updating UI based on state — React filled that gap beautifully.

Now Let’s break down how a React app starts after you run:

npx create-react-app my-app
cd my-app
npm start

What actually happens behind the scenes? Let’s unpack it step-by-step 👇

⚙️ Step 1: npx create-react-app — What It Does

This command:

  • Downloads and runs the latest version of the create-react-app tool (CRA).
  • Sets up a project with:
    • A preconfigured Webpack + Babel build system
    • Development server
    • Scripts and dependencies
  • Installs React, ReactDOM, and a bunch of tools inside node_modules.

Key folders/files created:

my-app/
├── node_modules/
├── public/
├── src/
│   └── index.js       👈 main entry point
├── package.json

Step 2: npm start — How the App Runs

When you run:

npm start

It’s actually running this line from package.json:

"scripts": {
  "start": "react-scripts start"
}

So it calls:

react-scripts start

🧠 What is react-scripts?

react-scripts is a package from Facebook that:

  • Runs a development server using Webpack Dev Server
  • Compiles JS/JSX using Babel
  • Watches your files for changes (HMR)
  • Starts a browser window at http://localhost:3000

It configures:

  • Webpack
  • Babel
  • ESLint
  • PostCSS
  • Source maps
    … all behind the scenes, so you don’t have to set up any configs manually.

📦 Libraries Involved

Tool / LibraryPurpose
ReactCore UI library (react)
ReactDOMRenders React into actual DOM (react-dom)
WebpackBundles your JS, CSS, images, etc.
BabelConverts modern JS/JSX to browser-friendly JS
Webpack Dev ServerStarts dev server with live reloading
react-scriptsRuns all the above with pre-made configs

🏗️ Step 3: Entry Point — src/index.js

The app starts here:

// src/index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);

  • ReactDOM.createRoot(...) finds the <div id="root"> in public/index.html.
  • Then renders the <App /> component into it.
  • The DOM inside the browser updates — and the user sees the UI.

✅ TL;DR

StepWhat Happens
npx create-react-appSets up a full React project with build tools
npm startCalls react-scripts start, which runs Webpack dev server
react-scriptsHandles build, hot reload, and environment setup
index.jsLoads React and renders your <App /> to the browser DOM
Browser OutputYou see your live React app at localhost:3000

6. Installing and Configuring React

Rails 8 provides a generator to bootstrap React + ESBuild.

  1. Run the React installer:
    rails javascript:install:react
    This will:
    • Install react and react-dom via npm.
    • Create an example app/javascript/components/HelloReact.jsx component.
    • Configure ESBuild to transpile JSX.
  2. Verify your application layout:
    In app/views/layouts/application.html.erb, ensure you have:
    <%= javascript_include_tag "application", type: "module", defer: true %>
  3. Mount the React component:
    Replace (or add) a div placeholder in an ERB view, e.g. app/views/home/index.html.erb:<div id="hello-react" data-props="{}"></div>
  4. Initialize mount point
    In app/javascript/application.js:
import "./components"

In app/javascript/components/index.js:

import React from "react"
import { createRoot } from "react-dom/client"
import HelloReact from "./HelloReact"

document.addEventListener("DOMContentLoaded", () => {
  const container = document.getElementById("hello-react")
  if (container) {
    const root = createRoot(container)
    const props = JSON.parse(container.dataset.props || "{}")
    root.render(<HelloReact {...props} />)
  }
})

Your React component will now render within the Rails view!

See you in Part 2 … 🚀

Setup 🛠 Rails 8 App – Part 4: Tailwind CSS 🎨 into the action

Does Tailwind Take Time?

  • If you haven’t used Tailwind before, expect a slight learning curve (1-2 days) to get comfortable.
  • But once you grasp utility classes, styling becomes faster than Bootstrap.

Fastest Way to Set Up Tailwind in Rails 8

1. Install Tailwind

   rails new myapp --css=tailwind

Or, if you already have a Rails app:

   ✗ bundle add tailwindcss-rails
     Fetching gem metadata from https://rubygems.org/.........
     Resolving dependencies...
     Fetching gem metadata from https://rubygems.org/.........
     Resolving dependencies...
     Fetching tailwindcss-ruby 4.0.17 (arm64-darwin)
     Installing tailwindcss-ruby 4.0.17 (arm64-darwin)
     Fetching tailwindcss-rails 4.2.1
     Installing tailwindcss-rails 4.2.1
   
  ✗ rails tailwindcss:install
      apply  /Users/abhilash/.local/share/mise/installs/ruby/3.4.1/lib/ruby/gems/3.4.0/gems/tailwindcss-rails-4.2.1/lib/install/install_tailwindcss.rb
  Add Tailwindcss container element in application layout
      insert    app/views/layouts/application.html.erb
      insert    app/views/layouts/application.html.erb
  Build into app/assets/builds
      create    app/assets/builds
      create    app/assets/builds/.keep
      append    .gitignore
  Add default /Users/xxxxx/rails/design_studio/app/assets/tailwind/application.css
      create    app/assets/tailwind/application.css
  Add default Procfile.dev
      create    Procfile.dev
  Ensure foreman is installed
         run    gem install foreman from "."
         Fetching foreman-0.88.1.gem
         Successfully installed foreman-0.88.1

Refer: https://tailwindcss.com/docs/installation/framework-guides/ruby-on-rails

Note: You can see this create a Procfile.dev file and installs foreman gem.

The foreman gem in Rails is used to manage and run multiple processes in development using a Procfile. It is particularly useful when your Rails application depends on several background services that need to run simultaneously.

Why is foreman used?

  • It allows you to define and manage multiple services (like Rails server, Tailwind compiler, Sidekiq, etc.) in a single command.
  • Ensures that all necessary processes start together, making development easier.
  • Helps simulate production environments where multiple services need to run concurrently.

Who is using foreman? Rails or Tailwind CSS?

  • The foreman gem itself is not specific to Rails or Tailwind CSS—it is a general-purpose process manager.
  • In our case, both Rails and Tailwind CSS are using foreman.
    • Rails: You can use foreman to start Rails server, background jobs, and Webpack.
    • Tailwind CSS: Since Tailwind needs a process to watch and compile CSS files (using npx tailwindcss -i input.css -o output.css --watch), foreman helps keep this process running.

What is Procfile.dev in Tailwind CSS?

  • When you install Tailwind in Rails, a Procfile.dev is created to define the processes required for development.
  • Example Procfile.dev for Tailwind and Rails:
    web: bin/rails server -p 3000
    js: yarn build --watch
    css: bin/rails tailwindcss:watch
    • web: Starts the Rails server.
    • js: Watches and compiles JavaScript files (if using esbuild or webpack).
    • css: Watches and compiles Tailwind CSS files.

How to use foreman?

  • Run the following command to start all processes defined in Procfile.dev: bin/dev
    • This starts the Rails server, the Tailwind CSS watcher, and other necessary processes.

The foreman gem is used as a process manager to run multiple services in development. In our case, both Rails and Tailwind CSS are using it. It ensures that Tailwind’s CSS compilation process runs alongside the Rails server.

2. Use Tailwind Classes in Views

Example:

   <div class="container mx-auto p-4">
     <h1 class="text-blue-500 text-3xl font-bold">Welcome to My App</h1>
     <button class="bg-green-500 text-white px-4 py-2 rounded">Click Me</button>
   </div>

This keeps your CSS minimal, avoids custom stylesheets, and helps you learn Tailwind naturally while building your app.

Here’s a Tailwind CSS Cheat Sheet to help you get started quickly with your Rails 8 app.

📌 1. Layout & Spacing

<div class="container mx-auto p-4">
  <div class="m-4 p-4 bg-gray-200">Margin & Padding</div>
</div>
  • mx-auto → Center content horizontally
  • p-4 → Padding (4 * 4px = 16px)
  • m-4 → Margin (4 * 4px = 16px)

🎨 2. Colors

<div class="bg-blue-500 text-white p-4">Blue Background</div>
<div class="text-red-600">Red Text</div>
  • Colors: gray, red, blue, green, etc.
  • Shades: 100 - 900 (lighter → darker)

Refer: https://tailwindcss.com/docs/background-color


🔤 3. Typography

<p class="text-lg font-bold">Large Bold Text</p>
<p class="text-sm italic">Small Italic Text</p>
  • text-lg → Large text
  • text-sm → Small text
  • font-bold → Bold text
  • italic → Italic text

📏 4. Width & Height

<div class="w-1/2 h-32 bg-green-300">50% Width, 128px Height</div>
  • w-1/2 → 50% width
  • w-full → Full width
  • h-32 → 128px height

🔳 5. Flexbox & Grid

<div class="flex justify-center items-center h-screen">
  <div class="bg-blue-500 p-4 text-white">Centered Box</div>
</div>
  • flex → Enables flexbox
  • justify-center → Centers horizontally
  • items-center → Centers vertically

🔘 6. Buttons

<button class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
  Click Me
</button>
  • hover:bg-blue-700 → Darker blue on hover
  • rounded → Rounded corners

🔗 7. Borders & Shadows

<div class="border border-gray-400 shadow-lg p-4">Border & Shadow</div>
  • border → Default border
  • border-gray-400 → Gray border
  • shadow-lg → Large shadow

📲 8. Responsive Design

<div class="p-4 text-sm md:text-lg lg:text-xl">
  Text size changes on different screens!
</div>
  • sm: → Small screens (≥ 640px)
  • md: → Medium screens (≥ 768px)
  • lg: → Large screens (≥ 1024px)

✨ 9. Animations & Transitions

<button class="bg-green-500 transition duration-300 hover:bg-green-700">
  Smooth Transition
</button>
  • transition → Enables animations
  • duration-300 → 300ms transition speed
  • hover:bg-green-700 → Change color on hover

🚀 Quick Setup for Your Rails 8 App

  1. Install Tailwind
   rails new myapp --css=tailwind
  1. Use Tailwind Classes in Views
   <div class="text-center p-6 text-2xl text-blue-500">Hello Tailwind!</div>

🔥 Bonus: Try Tailwind Play for live previews!

Tailwind in design studio

Check our Rails 8 app for tailwind implementation: https://github.com/abhilashak/design_studio/blob/main/bin/dev

I have added Tailwind CSS to our design_studio app. You can check the commit here: https://github.com/abhilashak/design_studio/commit/07db459

Track our Github Issue for tailwind task: https://github.com/abhilashak/design_studio/issues/1

The above issue will be automatically closed if you follow our Git commit message principle, that is mentioned in the below post:

Finally add the Tailwind Plugin Tailwind CSS IntelliSense for VS Code to make development easy.

to be continued.. 🚀