> ## 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

> Implement traditional email and password authentication

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:

```ts theme={null}
const result = await client.auth.register({
  email: "newuser@example.com",
  password: "secure-password-123",
  accountName: "My New Account",
});

console.log("User registered:", result.user.email);
console.log("Account created:", result.account.name);
```

<Note>
  The password must meet your SnackInstance's password requirements. The
  default minimum is 8 characters.
</Note>

### Registration Options

```ts theme={null}
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:

```ts theme={null}
const auth = await client.auth.loginWithPassword({
  account: "my-account", // Account slug or ID
  email: "user@example.com",
  password: "user-password",
});

console.log("Logged in as:", auth.user.email);
console.log("Account:", auth.account.name);
```

### Login Options

```ts theme={null}
interface LoginCredentials {
  account: string; // Account slug or ID
  email: string;
  password: string;
}
```

<Note>
  If you configured `defaultAccount` in the client, you can omit the account
  parameter from login requests.
</Note>

## Login with Default Account

```ts theme={null}
const client = new SnackBaseClient({
  baseUrl: "https://api.example.com",
  defaultAccount: "my-account",
});

// No need to specify account
const auth = await client.auth.loginWithPassword({
  email: "user@example.com",
  password: "user-password",
});
```

## Get Current User

After authentication, get the current user's profile:

```ts theme={null}
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:

```ts theme={null}
await client.auth.forgotPassword({
  email: "user@example.com",
});

console.log("Password reset email sent");
```

### 2. Reset Password with Token

Use the token from the reset email to set a new password:

```ts theme={null}
await client.auth.resetPassword({
  token: "reset-token-from-email",
  newPassword: "new-secure-password",
});

console.log("Password reset successfully");
```

## Email Verification

### Check Email Verification Status

```ts theme={null}
const user = await client.auth.getCurrentUser();

if (user.isEmailVerified) {
  console.log("Email is verified");
} else {
  console.log("Email is not verified");
}
```

### Send Verification Email

```ts theme={null}
await client.auth.sendVerificationEmail();

console.log("Verification email sent");
```

### Verify Email with Token

```ts theme={null}
await client.auth.verifyEmail("verification-token-from-email");

console.log("Email verified successfully");
```

### Resend Verification Email

```ts theme={null}
await client.auth.resendVerificationEmail();

console.log("Verification email resent");
```

## Complete Authentication Example

Here's a complete example showing the full authentication flow:

```ts theme={null}
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: "newuser@example.com",
      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: "user@example.com",
      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: "user@example.com",
    });

    // 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:

```tsx theme={null}
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:

```ts theme={null}
import {
  AuthenticationError,
  ValidationError,
  NetworkError,
} from "@snackbase/sdk";

try {
  await client.auth.loginWithPassword({
    email: "user@example.com",
    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:

```ts theme={null}
// 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:

```ts theme={null}
// 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:

```ts theme={null}
const client = new SnackBaseClient({
  baseUrl: "https://api.example.com",
  onAuthError: (error) => {
    // Redirect to login on auth error
    window.location.href = "/login";
  },
});
```

## Next Steps

* **[OAuth Guide](/sdk/js/auth/oauth)** - Add social login options
* **[API Keys](/sdk/js/auth/api-keys)** - Use API keys for server operations
* **[Error Handling](/sdk/js/errors/overview)** - Handle authentication errors
