Sinatra Integration
The Sinatra adapter mounts the core Rack auth object and provides request helpers plus Better Auth-specific SQL migration Rake tasks.
Install
gem "better_auth-sinatra"
gem "pg"bundle installConfigure And Mount
require "sinatra/base"
require "better_auth/sinatra"
class App < Sinatra::Base
register BetterAuth::Sinatra
better_auth at: "/api/auth" do |config|
config.secret = ENV.fetch("BETTER_AUTH_SECRET")
config.base_url = ENV.fetch("BETTER_AUTH_URL", "http://localhost:9292")
config.database = ->(options) {
BetterAuth::Adapters::Postgres.new(
options,
url: ENV.fetch("DATABASE_URL")
)
}
config.email_and_password = {
enabled: true
}
config.plugins = []
end
get "/dashboard" do
require_authentication
"Signed in as #{current_user.fetch("email")}"
end
endBy default this mounts Better Auth at /api/auth. The core Better Auth router
handles internal routes such as /ok, /sign-up/email, and plugin endpoints.
Helpers
Available helpers:
current_sessioncurrent_userauthenticated?require_authentication
require_authentication halts the Sinatra request with 401 when no Better
Auth user is present.
Sinatra helpers resolve sessions through the core get-session API path, so
Better Auth plugin hooks that affect session lookup, such as the bearer plugin,
run for current_user and require_authentication. Helper session lookup may
emit Better Auth Set-Cookie headers when stale cookies need to be cleared or
session cookies need to be refreshed.
Rake Tasks
Sinatra does not have a Rails-style generator or built-in migration command. Load the Better Auth tasks from your app Rakefile:
require "better_auth/sinatra/tasks"Create the default config and migration directory:
rake better_auth:installGenerate SQL for the configured Better Auth schema:
BETTER_AUTH_DIALECT=postgres rake better_auth:generate:migrationRun pending Better Auth SQL migrations:
rake better_auth:migrateGenerated SQL files live in db/better_auth/migrate.
Limitations
- ActiveRecord-backed Sinatra migrations are not supported yet.
- The Rake migration runner supports Better Auth core SQL adapters that expose a SQL connection and dialect.
- Memory, MongoDB, and arbitrary custom adapters cannot run SQL migrations.
- Apps that already use
sinatra-activerecordcan still mount Better Auth, but should manage ActiveRecord migrations themselves until optional support is added.