Rails Integration

The Rails adapter mounts the core Rack auth object and provides generators, ActiveRecord persistence, schema-driven associations, migrations, and controller helpers.

Install

Gemfile
gem "better_auth-rails"
Terminal
bundle install
bin/rails generate better_auth:install

The install generator creates:

  • config/initializers/better_auth.rb
  • a Better Auth migration for the configured core/plugin schema

Configure

config/initializers/better_auth.rb
BetterAuth::Rails.configure do |config|
  config.secret =
    Rails.application.credentials.dig(:better_auth, :secret) ||
    Rails.application.credentials.secret_key_base ||
    Rails.application.secret_key_base

  config.base_url = ENV["BETTER_AUTH_URL"]
  config.base_path = "/api/auth"

  config.email_and_password do |auth|
    auth.enabled = true
    auth.require_email_verification = true
  end

  config.plugins = [
    # BetterAuth::Plugins.username
  ]
end

Rails uses BetterAuth::Rails::ActiveRecordAdapter by default. For a custom adapter, assign config.database directly.

Mount Routes

config/routes.rb
Rails.application.routes.draw do
  better_auth
end

By default this mounts Better Auth at /api/auth.

Customize the path:

config/routes.rb
Rails.application.routes.draw do
  better_auth at: "/auth"
end

Run Migrations

Terminal
bin/rails db:migrate

When you add plugins that introduce schema tables or fields, regenerate a migration before migrating a new app:

Terminal
bin/rails generate better_auth:migration

Controller Helpers

app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  include BetterAuth::Rails::ControllerHelpers
end

Available helpers:

  • current_session
  • current_user
  • authenticated?
  • require_authentication

Example:

app/controllers/dashboard_controller.rb
class DashboardController < ApplicationController
  before_action :require_authentication

  def show
    @user = current_user
  end
end

On this page