Identity & Access

Mission-Critical Authentication

Afribase Auth provides a hardened, enterprise-grade authentication solution built on the industry-standard **GoTrue** API. Deploy secure social login, magic links, and multi-factor authentication across your entire organization with zero infrastructure management.

Identity Providers

Email & Magic Links

Standard password-based login or secure, passwordless magic links delivered via email.

OAuth Providers

Instantly enable social login with Google, GitHub, Slack, Discord, and dozens of others.

WebAuthn (Passkeys)

Coming soon. Modern, biometric-based passwordless authentication methods.

Implementation

Afribase provides a strongly-typed interface for managing authentication. Below are the core methods available in our SDKs (JavaScript, Python, Dart).

01

Sign Up / Sign In

Users can sign up for a new account or sign in with their existing credentials.

JavaScript

typescript
// Sign Up
const { data, error } = await afribase.auth.signUp({
  email: 'user@example.com',
  password: 'securePassword123'
});

// Sign In with Password
const { data, error } = await afribase.auth.signInWithPassword({
  email: 'user@example.com',
  password: 'securePassword123'
});

Python

python
# Sign Up
client.auth.sign_up(email="user@example.com", password="securePassword123")

# Sign In with Password
client.auth.sign_in_with_password(email="user@example.com", password="securePassword123")

Dart / Flutter

dart
// Sign Up
await client.auth.signUp(email: 'user@example.com', password: 'securePassword123');

// Sign In with Password
await client.auth.signInWithPassword(email: 'user@example.com', password: 'securePassword123');
02

Passwordless & OAuth

Send one-time passwords (OTP) or magic links, and handle Social Logins like Google or GitHub.

JavaScript

typescript
// Send OTP / Magic Link
await afribase.auth.signInWithOtp({ email: 'user@example.com' });

// Social Login
const { url } = await afribase.auth.signInWithOAuth({ provider: 'google' });

Python

python
# Send OTP / Magic Link
client.auth.sign_in_with_otp(email="user@example.com")

# Social Login
url = client.auth.sign_in_with_oauth(provider="google")

Dart / Flutter

dart
// Send OTP / Magic Link
await client.auth.signInWithOtp(email: 'user@example.com');

// Social Login
final url = await client.auth.signInWithOAuth(provider: 'google');
03

Session Management

Listen to authentication state changes across your application to handle navigation and session persistence.

JavaScript

typescript
afribase.auth.onAuthStateChange((event, session) => {
  console.log('Auth Event:', event); // 'SIGNED_IN', 'SIGNED_OUT'
});

Python

python
def on_auth_change(event, session):
    print(f"Auth state changed: {event}")

client.auth.on_auth_state_change(on_auth_change)

Dart

dart
client.auth.onAuthStateChange((event, session) => {
  print('Auth state changed to: $event');
});
Leverage our useAuthInactivity() hook in your React applications to automatically handle session expiration and redirect users to the sign-in page.

Custom SMTP

By default, Afribase sends auth emails (confirmations, password resets, magic links) through the platform's shared mailer. Configure your own SMTP provider to send from your own domain — essential for production apps.

Go to your project → Auth tabCustom SMTP → click Configure SMTP. Fill in the credentials, use Send test email to verify before saving.

Supported Providers

ProviderHostPortUsernamePassword
Mailtrap Livetest onlysend.smtp.mailtrap.io587apiYour Mailtrap API token
Mailtrap Sandboxtest onlysandbox.smtp.mailtrap.io2525Inbox usernameInbox password
Brevo (Sendinblue)smtp-relay.brevo.com587Your Brevo emailSMTP Key from Brevo dashboard
Resendsmtp.resend.com465resendYour Resend API key
SendGridsmtp.sendgrid.net587apikeyYour SendGrid API key
Postmarksmtp.postmarkapp.com587Server API tokenServer API token
Mailgunsmtp.mailgun.org587SMTP loginSMTP password
Gmailsmtp.gmail.com587your@gmail.comApp Password (16 chars)
Zoho Mailsmtp.zoho.com465your@zohomail.comAccount or app password
AWS SESemail-smtp.us-east-1.amazonaws.com587SES SMTP usernameSES SMTP password

Mailtrap Live: Mailtrap Live sends to real inboxes but requires domain verification at mailtrap.io → Sending Domains before emails are delivered.

Mailtrap Sandbox: Sandbox only. Emails appear in your Mailtrap inbox for inspection — real users never receive them. Perfect for development.

Brevo: Create your SMTP key under Brevo dashboard → SMTP & API → SMTP. The username is your Brevo account email, not "apikey".

Gmail: You must enable 2-Step Verification on your Google account, then generate an App Password at myaccount.google.com → Security → App passwords.

AWS SES: Replace us-east-1 in the host with your SES region (e.g. eu-west-1). Create dedicated SMTP credentials in the SES console — do not use your AWS access key.

Step-by-step setup

01

Open Auth settings

Navigate to your project → Auth tab → Custom SMTP section → click Configure SMTP.
02

Pick a provider preset

Click one of the provider quick-fill buttons (Mailtrap Live, Brevo, Resend…) to auto-fill the host and port. Then enter your username and password/API key.
03

Send a test email

Enter your own email in the Send test email field and click Send test. A green checkmark confirms the credentials work before anything is saved.
04

Save & Enable

Click Save & Enable SMTP. Your GoTrue auth container restarts in the background (takes ~30 s) and will use your provider for all subsequent auth emails.
If you use Mailtrap Live or Resend, you must verify your sending domain in the respective dashboard before emails will reach real inboxes. Without verification, delivery is silently blocked.

Email Templates

Every auth email your users receive can be fully customised — subject line and HTML body. Templates are stored per-project and injected into GoTrue at container start.

Confirmation

Trigger: User signs up with email/password

CTA: Verify email address

Invite

Trigger: Admin invites a user to the project

CTA: Accept workspace invitation

Recovery

Trigger: User requests a password reset

CTA: Reset password

Magic Link

Trigger: User signs in with a magic link

CTA: Passwordless login

Email Change

Trigger: User changes their email address

CTA: Confirm new email

Template Variables

GoTrue injects these variables at send time. Use them inside your HTML template body.

VariableDescriptionExample value
{{ .ConfirmationURL }}Full verification / action URL. Use this as the href for your CTA button.https://myapp.com/auth/confirm?token=…
{{ .Token }}6-digit OTP code shown when link-based flow is disabled.482916
{{ .TokenHash }}Hashed token for server-side verification endpoints.pkce_…
{{ .SiteURL }}The Site URL configured in your auth settings.https://myapp.com
{{ .Email }}The recipient's email address.user@example.com
{{ .NewEmail }}New email (only in Email Change template).new@example.com
{{ .RedirectTo }}The redirect_to URL passed during sign-up/sign-in.https://myapp.com/dashboard

Minimal HTML template example

html
<!DOCTYPE html>
<html>
<body style="background:#000;font-family:sans-serif;padding:40px;">
  <div style="max-width:560px;margin:0 auto;background:#111;border:1px solid #222;
              border-radius:16px;padding:40px;color:#fff;">
    <h2 style="color:#10b981;margin:0 0 16px;">Verify your email</h2>
    <p style="color:#a1a1aa;line-height:1.6;">
      Click the button below to confirm your account on <strong>MyApp</strong>.
    </p>
    <a href="{{ .ConfirmationURL }}"
       style="display:inline-block;margin-top:24px;padding:14px 28px;
              background:#10b981;color:#000;border-radius:10px;
              font-weight:700;text-decoration:none;">
      Verify Email
    </a>
    <p style="margin-top:32px;font-size:12px;color:#555;">
      Or copy this link: {{ .ConfirmationURL }}
    </p>
  </div>
</body>
</html>

How to edit templates

01

Open the template editor

Project → Auth tab → scroll to Email Templates → click the template card you want to edit (Confirmation, Recovery, etc.).
02

Edit subject and body

Update the Subject Line and paste your custom HTML into the body editor. Use the Inject variable buttons to insert GoTrue template variables at the cursor.
03

Preview before saving

Toggle Show Preview to render the HTML in an iframe so you can see exactly how it looks.
04

Save

Click Save Template Changes. The new template is applied immediately — no container restart required.
Always include {{ .ConfirmationURL }} in your Confirmation, Recovery, and Magic Link templates. If this variable is missing, users will receive an email with a broken or empty action link.

Email Service

Once you configure a custom SMTP provider, Afribase doubles as a full transactional email service for your application. Send welcome emails, invoices, alerts, or any custom email directly from the SDK — no extra email library required.

1. Configure SMTP

Add your SMTP credentials once in the Auth settings. Afribase stores them securely and uses them for all email delivery.

2. Create Templates

Design reusable HTML email templates in the dashboard with custom variables like {{ .name }} and {{ .plan }}.

3. Call the SDK

Use afribase.email.send() from JS, Python, or Flutter. Pass a template ID or raw HTML — Afribase handles the rest.

Your SMTP credentials are never exposed to the SDK or the browser. The SDK authenticates with your project's anon key — Afribase looks up the SMTP config server-side and sends on your behalf.

Quick Start

01

Configure SMTP

Go to your project → Auth tab → Custom SMTP → add your credentials and click Send test email to verify they work.
02

(Optional) Create a reusable template

In the same Auth tab, scroll to Custom Email Templates → click New Template. Give it an ID (e.g. welcome), write your HTML using {{ .name }} placeholders, and save.
03

Install the SDK

JavaScript / TypeScript

bash
npm install @afribase/afribase-js

Python

bash
pip install afribase

Flutter / Dart — pubspec.yaml

yaml
dependencies:
  afribase_flutter: ^0.3.0
04

Send your first email

Call client.email.send() from anywhere in your application.

Send with a saved template

Reference a template by its ID. Variables in the template ({{ .name }}, {{ .plan }}, etc.) are replaced with the values you pass in template_vars.

JavaScript / TypeScript

typescript
import { createClient } from '@afribase/afribase-js';

const afribase = createClient(PROJECT_URL, ANON_KEY);

// Send using a saved template
const { data, error } = await afribase.email.send({
  to: 'user@example.com',
  template_id: 'welcome',          // ID of the template you created in the dashboard
  template_vars: {
    name: 'John Doe',
    plan: 'Pro',
    company: 'Acme Corp',
  },
});

if (error) console.error('Email failed:', error);
else console.log('Sent:', data?.status);

Python

python
from afribase import create_client

client = create_client(PROJECT_URL, ANON_KEY)

result = client.email.send(
    to="user@example.com",
    template_id="welcome",
    template_vars={
        "name": "John Doe",
        "plan": "Pro",
        "company": "Acme Corp",
    },
)

if result["error"]:
    print("Email failed:", result["error"])
else:
    print("Sent:", result["data"]["status"])

Dart / Flutter

dart
import 'package:afribase_flutter/afribase.dart';

final client = AfribaseClient(PROJECT_URL, ANON_KEY);

final response = await client.email.send(
  to: 'user@example.com',
  templateId: 'welcome',
  templateVars: {
    'name': 'John Doe',
    'plan': 'Pro',
    'company': 'Acme Corp',
  },
);

if (response.hasError) {
  print('Email failed: ${response.error}');
} else {
  print('Sent: ${response.data}');
}

Send raw HTML (no template)

Skip templates entirely and pass a subject and HTML body directly. Useful for one-off transactional emails generated server-side.

JavaScript / TypeScript

typescript
await afribase.email.send({
  to: 'user@example.com',
  subject: 'Your invoice is ready',
  html: `
    <div style="background:#000;padding:40px;font-family:sans-serif;">
      <h2 style="color:#10b981;">Invoice #1042</h2>
      <p style="color:#a1a1aa;">Amount due: <strong style="color:#fff;">$49.00</strong></p>
      <a href="https://myapp.com/invoices/1042"
         style="display:inline-block;margin-top:20px;padding:12px 24px;
                background:#10b981;color:#000;border-radius:8px;text-decoration:none;">
        View Invoice
      </a>
    </div>
  `,
  from: 'billing@myapp.com',     // optional: override from address
  from_name: 'MyApp Billing',    // optional: override sender name
});

Python

python
client.email.send(
    to="user@example.com",
    subject="Your invoice is ready",
    html="""
      <div style="background:#000;padding:40px;font-family:sans-serif;">
        <h2 style="color:#10b981;">Invoice #1042</h2>
        <p style="color:#a1a1aa;">Amount due: <strong style="color:#fff;">$49.00</strong></p>
      </div>
    """,
    from_="billing@myapp.com",
    from_name="MyApp Billing",
)

Dart / Flutter

dart
await client.email.send(
  to: 'user@example.com',
  subject: 'Your invoice is ready',
  html: '''
    <div style="background:#000;padding:40px;">
      <h2 style="color:#10b981;">Invoice #1042</h2>
    </div>
  ''',
  from: 'billing@myapp.com',
  fromName: 'MyApp Billing',
);

List saved templates from the SDK

Fetch all custom templates you created in the dashboard. Useful for building dynamic email UIs in your own admin panel.

typescript
// JavaScript
const { data: templates, error } = await afribase.email.listTemplates();
// templates: [{ id, name, subject, html, created_at, updated_at }, ...]

// Python
result = client.email.list_templates()
templates = result["data"]

// Dart
final response = await client.email.listTemplates();
final templates = response.data; // List<EmailTemplate>

Custom template variables

Any key you pass in template_vars becomes available in your template as {{ .KeyName }}. Variable names are case-sensitive.

In template_varsUse in HTML asExample value
"name": "John Doe"{{ .name }}John Doe
"plan": "Pro"{{ .plan }}Pro
"company": "Acme Corp"{{ .company }}Acme Corp
"amount": "$49.00"{{ .amount }}$49.00
"link": "https://myapp.com/activate"{{ .link }}https://myapp.com/activate
"code": "PROMO20"{{ .code }}PROMO20
html
<!-- Example template HTML using custom variables -->
<div style="background:#000;padding:40px;font-family:sans-serif;">
  <h2 style="color:#10b981;">Welcome, {{ .name }}!</h2>
  <p style="color:#a1a1aa;">
    You're now on the <strong style="color:#fff;">{{ .plan }}</strong> plan.
    We're thrilled to have {{ .company }} on board.
  </p>
  <a href="{{ .link }}"
     style="display:inline-block;margin-top:24px;padding:14px 28px;
            background:#10b981;color:#000;border-radius:10px;
            font-weight:700;text-decoration:none;">
    Get Started
  </a>
</div>

API Reference — email.send()

ParameterTypeRequiredDescription
tostringYesRecipient email address.
template_idstringNoID of a saved custom template. When provided, subject and html are taken from the template.
template_varsobjectNoKey-value pairs substituted as {{ .Key }} inside the template subject and body.
subjectstringConditionalEmail subject line. Required when template_id is not provided.
htmlstringConditionalFull HTML email body. Required when template_id is not provided.
fromstringNoOverride the from address. Defaults to the SMTP admin email in your settings.
from_namestringNoOverride the sender display name. Defaults to the SMTP sender name in your settings.
email.send() requires your project to have Custom SMTP configured and enabled in the Auth settings. If no SMTP is set, Afribase falls back to the platform shared mailer which has daily rate limits and no custom from address.

Global Policies

Organize users into User Groups and assign global permissions that dictate access across all services (Database, Storage, Edge Functions).

Access Control (RBAC)

Fine-grained Role Based Access Control for your entire organization.

© 2026 Afribase Cloud Infrastructure. Produced by Altris Product Systems.