Email & Password
Email/password authentication is built into better_auth.
Enable Email And Password
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
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.
status, headers, body = auth.api.sign_up_email(
{
body: {
name: "Ada Lovelace",
email: "ada@example.com",
password: "password123"
},
as_response: true
}
)Sign In
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
status, headers, body = auth.api.sign_out(
{
headers: {
"cookie" => request.env["HTTP_COOKIE"]
},
as_response: true
}
)Email Verification
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:
auth = BetterAuth.auth(
secret: ENV.fetch("BETTER_AUTH_SECRET"),
email_and_password: {
enabled: true,
require_email_verification: true
}
)Send verification manually:
auth.api.send_verification_email(
body: {
email: "ada@example.com",
callback_url: "/dashboard"
}
)Password Reset
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:
auth.api.request_password_reset(
body: {
email: "ada@example.com",
redirect_to: "/reset-password"
}
)Reset the password:
auth.api.reset_password(
body: {
token: params.fetch("token"),
new_password: "new-password123"
}
)