Skip to content

Basic usage

The installation example enables email/password and session management. Its authentication endpoints are available under /api/auth.

Terminal window
curl -i -c cookies.txt http://localhost:3000/api/auth/sign-up/email \
-H 'Content-Type: application/json' \
-H 'Origin: http://localhost:3000' \
-d '{"name":"Ada","email":"ada@example.com","password":"a-long-example-password"}'

Successful signup signs the user in by default and returns session cookies. Requiring email verification or disabling automatic sign-in changes that behavior.

Terminal window
curl -i -c cookies.txt http://localhost:3000/api/auth/sign-in/email \
-H 'Content-Type: application/json' \
-H 'Origin: http://localhost:3000' \
-d '{"email":"ada@example.com","password":"a-long-example-password"}'
Terminal window
curl -b cookies.txt http://localhost:3000/api/auth/get-session

In an Axum handler, use a typed extractor:

use crate::auth_schema::AppAuthSchema;
use better_auth::integrations::axum::CurrentSession;
use better_auth::prelude::AuthUser;
async fn profile(session: CurrentSession<AppAuthSchema>) -> String {
format!("Signed in as {}", session.user.id())
}

CurrentSession rejects requests without a valid session with HTTP 401. Use OptionalSession when a route also serves anonymous users. See Axum for mounting protected handlers.

Terminal window
curl -i -b cookies.txt -c cookies.txt http://localhost:3000/api/auth/sign-out \
-X POST -H 'Origin: http://localhost:3000'

Forward all response cookie headers when embedding authentication in a custom HTTP host.

Call the request handler from Rust with the same body and headers as an HTTP request:

use crate::auth_schema::AppAuthSchema;
use better_auth::prelude::{AuthRequest, AuthResponse, HttpMethod};
use better_auth::{AuthResult, BetterAuth};
async fn sign_in(
auth: &BetterAuth<AppAuthSchema>,
email: &str,
password: &str,
) -> AuthResult<AuthResponse> {
let mut request = AuthRequest::new(HttpMethod::Post, "/api/auth/sign-in/email");
request
.headers
.insert("content-type".into(), "application/json".into());
request
.headers
.insert("origin".into(), "http://localhost:3000".into());
request.body = Some(serde_json::to_vec(&serde_json::json!({
"email": email,
"password": password,
}))?);
auth.handle_request(request).await
}

Return the response to the caller, including all cookies. See other frameworks for response conversion.

For frontend sign-up, sign-in, session hooks, and sign-out, use the official Better Auth basic usage guide and client setup documentation.