Email & Password

Email/password authentication is built into better_auth.

Enable Email And Password

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,
    auto_sign_in: true
  },
  database: BetterAuth::Adapters::Postgres.new(
    url: ENV.fetch("DATABASE_URL")
  )
)

Sign Up

server.rb
result = auth.api.sign_up_email(
  body: {
    name: "Ada Lovelace",
    email: "ada@example.com",
    password: "password123",
    image: "https://example.com/avatar.png",
    callback_url: "/dashboard"
  }
)

user = result.fetch(:user)
token = result.fetch(:token)

Use as_response: true when you need the Rack response and Set-Cookie headers.

server.rb
status, headers, body = auth.api.sign_up_email(
  {
    body: {
      name: "Ada Lovelace",
      email: "ada@example.com",
      password: "password123"
    },
    as_response: true
  }
)

Sign In

server.rb
status, headers, body = auth.api.sign_in_email(
  {
    body: {
      email: "ada@example.com",
      password: "password123",
      remember_me: true,
      callback_url: "/dashboard"
    },
    as_response: true
  }
)

Sign Out

server.rb
status, headers, body = auth.api.sign_out(
  {
    headers: {
      "cookie" => request.env["HTTP_COOKIE"]
    },
    as_response: true
  }
)

Email Verification

config/auth.rb
auth = BetterAuth.auth(
  secret: ENV.fetch("BETTER_AUTH_SECRET"),
  email_verification: {
    send_verification_email: ->(data, request = nil) {
      UserMailer.verify_email(
        data.fetch(:user),
        data.fetch(:url)
      ).deliver_later
    }
  }
)

Require verification before sign-in:

config/auth.rb
auth = BetterAuth.auth(
  secret: ENV.fetch("BETTER_AUTH_SECRET"),
  email_and_password: {
    enabled: true,
    require_email_verification: true
  }
)

Send verification manually:

server.rb
auth.api.send_verification_email(
  body: {
    email: "ada@example.com",
    callback_url: "/dashboard"
  }
)

Password Reset

config/auth.rb
auth = BetterAuth.auth(
  secret: ENV.fetch("BETTER_AUTH_SECRET"),
  email_and_password: {
    enabled: true,
    send_reset_password: ->(data, request = nil) {
      UserMailer.reset_password(
        data.fetch(:user),
        data.fetch(:url)
      ).deliver_later
    }
  }
)

Request a reset:

server.rb
auth.api.request_password_reset(
  body: {
    email: "ada@example.com",
    redirect_to: "/reset-password"
  }
)

Reset the password:

server.rb
auth.api.reset_password(
  body: {
    token: params.fetch("token"),
    new_password: "new-password123"
  }
)

On this page