Installation
Install The Gem
For Rack, Sinatra, Hanami, Roda, or another Rack-based app:
gem "better_auth"For Rails:
gem "better_auth-rails"For Hanami 2.3+ apps:
gem "better_auth-hanami"Then install dependencies:
bundle installSet Environment Variables
Set a high-entropy secret and the public base URL of your app.
BETTER_AUTH_SECRET=
BETTER_AUTH_URL=http://localhost:3000You can generate a secret with:
openssl rand -base64 32Use a real secret outside test. The Ruby port allows the default test secret only in test environments.
Create A Better Auth Instance
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:
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:
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:
bin/rails generate better_auth:installFor Hanami:
bundle exec rake better_auth:init
bin/hanami db migrateMount The Handler
Rack:
require_relative "config/auth"
map "/api/auth" do
run auth
endRails:
Rails.application.routes.draw do
better_auth
endThe default base path is /api/auth.
Verify The Server
Send a request to the health endpoint:
curl http://localhost:3000/api/auth/okExpected response:
{ "ok": true }