Documentation Index
Fetch the complete documentation index at: https://docs.snackbase.dev/llms.txt
Use this file to discover all available pages before exploring further.
Email and password authentication is the most common authentication method. This guide shows you how to implement it with the SnackBase JavaScript SDK.
User Registration
Register a new user with email and password:
const result = await client.auth.register({
email: "[email protected]",
password: "secure-password-123",
accountName: "My New Account",
});
console.log("User registered:", result.user.email);
console.log("Account created:", result.account.name);
The password must meet your SnackInstance’s password requirements. The
default minimum is 8 characters.
Registration Options
interface RegisterData {
email: string;
password: string;
accountName: string;
accountSlug?: string; // Optional custom account slug
}
User Login
Log in an existing user with email and password:
const auth = await client.auth.loginWithPassword({
account: "my-account", // Account slug or ID
email: "[email protected]",
password: "user-password",
});
console.log("Logged in as:", auth.user.email);
console.log("Account:", auth.account.name);
Login Options
interface LoginCredentials {
account: string; // Account slug or ID
email: string;
password: string;
}
If you configured defaultAccount in the client, you can omit the account
parameter from login requests.
Login with Default Account
const client = new SnackBaseClient({
baseUrl: "https://api.example.com",
defaultAccount: "my-account",
});
// No need to specify account
const auth = await client.auth.loginWithPassword({
email: "[email protected]",
password: "user-password",
});
Get Current User
After authentication, get the current user’s profile:
const user = await client.auth.getCurrentUser();
console.log(user.id);
console.log(user.email);
console.log(user.fullName);
console.log(user.isActive);
console.log(user.isEmailVerified);
Password Reset Flow
1. Request Password Reset
Send a password reset email to the user:
await client.auth.forgotPassword({
email: "[email protected]",
});
console.log("Password reset email sent");
2. Reset Password with Token
Use the token from the reset email to set a new password:
await client.auth.resetPassword({
token: "reset-token-from-email",
newPassword: "new-secure-password",
});
console.log("Password reset successfully");
Email Verification
Check Email Verification Status
const user = await client.auth.getCurrentUser();
if (user.isEmailVerified) {
console.log("Email is verified");
} else {
console.log("Email is not verified");
}
Send Verification Email
await client.auth.sendVerificationEmail();
console.log("Verification email sent");
Verify Email with Token
await client.auth.verifyEmail("verification-token-from-email");
console.log("Email verified successfully");
Resend Verification Email
await client.auth.resendVerificationEmail();
console.log("Verification email resent");
Complete Authentication Example
Here’s a complete example showing the full authentication flow:
import { SnackBaseClient } from "@snackbase/sdk";
const client = new SnackBaseClient({
baseUrl: "https://api.example.com",
defaultAccount: "my-account",
});
// Register a new user
async function register() {
try {
const result = await client.auth.register({
email: "[email protected]",
password: "SecurePass123!",
accountName: "My Account",
});
console.log("Registration successful:", result.user.email);
// Send verification email
await client.auth.sendVerificationEmail();
console.log("Verification email sent");
} catch (error) {
console.error("Registration failed:", error);
}
}
// Login
async function login() {
try {
const auth = await client.auth.loginWithPassword({
email: "[email protected]",
password: "SecurePass123!",
});
console.log("Login successful:", auth.user.email);
// Get current user
const user = await client.auth.getCurrentUser();
console.log("Current user:", user);
} catch (error) {
console.error("Login failed:", error);
}
}
// Reset password
async function resetPassword() {
try {
// Step 1: Request reset
await client.auth.forgotPassword({
email: "[email protected]",
});
// Step 2: User receives email with token
// Step 3: Reset with token
const token = "token-from-email";
await client.auth.resetPassword({
token,
newPassword: "NewSecurePass456!",
});
console.log("Password reset successful");
} catch (error) {
console.error("Password reset failed:", error);
}
}
// Logout
async function logout() {
await client.auth.logout();
console.log("Logged out");
}
React Integration
Using email/password authentication with React:
import { useAuth } from "@snackbase/sdk/react";
function LoginForm() {
const { login, logout, user, isLoading } = useAuth();
const handleLogin = async (e: React.FormEvent) => {
e.preventDefault();
const email = (e.currentTarget.elements.namedItem("email") as HTMLInputElement).value;
const password = (e.currentTarget.elements.namedItem("password") as HTMLInputElement).value;
try {
await login({ email, password });
} catch (error) {
console.error("Login failed:", error);
}
};
if (isLoading) return <p>Loading...</p>;
if (user) {
return (
<div>
<p>Welcome, {user.email}!</p>
<button onClick={logout}>Logout</button>
</div>
);
}
return (
<form onSubmit={handleLogin}>
<input name="email" type="email" placeholder="Email" required />
<input name="password" type="password" placeholder="Password" required />
<button type="submit">Login</button>
</form>
);
}
Error Handling
Handle common authentication errors:
import {
AuthenticationError,
ValidationError,
NetworkError,
} from "@snackbase/sdk";
try {
await client.auth.loginWithPassword({
email: "[email protected]",
password: "wrong-password",
});
} catch (error) {
if (error instanceof AuthenticationError) {
console.error("Invalid credentials");
} else if (error instanceof ValidationError) {
console.error("Validation error:", error.fields);
} else if (error instanceof NetworkError) {
console.error("Network error - please check your connection");
} else {
console.error("Unknown error:", error);
}
}
Security Best Practices
1. Password Requirements
Ensure your SnackBase instance has secure password requirements:
- Minimum 8 characters
- Mix of letters, numbers, and symbols
- No common passwords
2. HTTPS Only
Always use HTTPS in production:
// Good
const client = new SnackBaseClient({
baseUrl: "https://api.example.com",
});
// Bad - never use HTTP in production
const client = new SnackBaseClient({
baseUrl: "http://api.example.com",
});
3. Token Storage
Use appropriate storage for your use case:
// For web apps - persists across sessions
const client = new SnackBaseClient({
storageBackend: "localStorage",
});
// For shared/public devices - cleared on tab close
const client = new SnackBaseClient({
storageBackend: "sessionStorage",
});
4. Auto-Logout on Token Expiry
Configure the SDK to handle token expiry:
const client = new SnackBaseClient({
baseUrl: "https://api.example.com",
onAuthError: (error) => {
// Redirect to login on auth error
window.location.href = "/login";
},
});
Next Steps