Installation

Install The Gem

For Rack, Sinatra, Hanami, Roda, or another Rack-based app:

Gemfile
gem "better_auth"

For Rails:

Gemfile
gem "better_auth-rails"

For Hanami 2.3+ apps:

Gemfile
gem "better_auth-hanami"

Then install dependencies:

Terminal
bundle install

Set Environment Variables

Set a high-entropy secret and the public base URL of your app.

.env
BETTER_AUTH_SECRET=
BETTER_AUTH_URL=http://localhost:3000

You can generate a secret with:

Terminal
openssl rand -base64 32

Use a real secret outside test. The Ruby port allows the default test secret only in test environments.

Create A Better Auth Instance

config/auth.rb
require "better_auth"

auth = BetterAuth.auth(
  secret: ENV.fetch("BETTER_AUTH_SECRET"),
  base_url: ENV.fetch("BETTER_AUTH_URL", "http://localhost:3000"),
  email_and_password: {
    enabled: true
  },
  database: BetterAuth::Adapters::Memory.new
)

The memory adapter is useful for development and tests. Production apps should use PostgreSQL, MySQL, the Rails ActiveRecord adapter, or the Hanami Sequel adapter.

Configure Persistence

PostgreSQL:

config/auth.rb
auth = BetterAuth.auth(
  secret: ENV.fetch("BETTER_AUTH_SECRET"),
  base_url: ENV.fetch("BETTER_AUTH_URL"),
  database: BetterAuth::Adapters::Postgres.new(
    url: ENV.fetch("DATABASE_URL")
  )
)

MySQL:

config/auth.rb
auth = BetterAuth.auth(
  secret: ENV.fetch("BETTER_AUTH_SECRET"),
  base_url: ENV.fetch("BETTER_AUTH_URL"),
  database: BetterAuth::Adapters::MySQL.new(
    url: ENV.fetch("DATABASE_URL")
  )
)

Rails apps normally use the generated ActiveRecord adapter configuration:

Terminal
bin/rails generate better_auth:install

For Hanami:

Terminal
bundle exec rake better_auth:init
bin/hanami db migrate

Mount The Handler

Rack:

config.ru
require_relative "config/auth"

map "/api/auth" do
  run auth
end

Rails:

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

The default base path is /api/auth.

Verify The Server

Send a request to the health endpoint:

Terminal
curl http://localhost:3000/api/auth/ok

Expected response:

{ "ok": true }

On this page