Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion mintlify/docs/docs.json
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,9 @@
"sdk/overview",
"sdk/auth",
"sdk/database",
"sdk/storage"
"sdk/storage",
"sdk/schema",
"sdk/mail"
]
},
{
Expand Down
180 changes: 101 additions & 79 deletions mintlify/docs/sdk/auth.mdx
Original file line number Diff line number Diff line change
@@ -1,163 +1,185 @@
---
title: "Auth"
description: "Create accounts, log in users, and retrieve the current session with the SDK auth module."
keywords: ["auth", "authentication", "login", "signup", "sdk"]
description: "Manage user accounts, sessions, and social authentication with the SDK auth module."
keywords: ["auth", "authentication", "login", "signup", "sdk", "social auth", "oauth"]
---

Access auth methods via `client.auth`. The module stores the session token from `login()` automatically, so you do not need to thread it through subsequent calls manually.
You can access auth methods via `client.auth`. When you call `login()` or `refreshToken()`, the module stores the `accessToken` and uses it for subsequent authenticated requests such as `me()` or `updateProfile()`.

## signUp
## `signUp`

Create a new user account.

```typescript
signUp(payload: SignUpPayload): Promise<AuthUser>
```

**Parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `email` | `string` | Yes | User's email address. |
| `password` | `string` | Yes | User's password. |
| `name` | `string` | No | Display name. |

**Returns** `AuthUser`

```typescript
interface AuthUser {
_id: string;
email: string;
name?: string;
[key: string]: unknown;
}
```

**Example**

```typescript
const user = await client.auth.signUp({
email: 'alice@example.com',
password: 'secret123',
username: 'alice_dev',
name: 'Alice',
});

console.log(user._id); // '507f1f77bcf86cd799439011'
```

---

## login
## `login`

Authenticate an existing user. The returned token is stored internally in the auth module and used automatically by `me()`.
Authenticate an existing user. The returned `accessToken` is stored internally.

```typescript
login(payload: LoginPayload): Promise<AuthResponse>
```

**Parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `email` | `string` | Yes | User's email address. |
| `password` | `string` | Yes | User's password. |

**Returns** `AuthResponse`

```typescript
interface AuthResponse {
token: string; // accessToken — store this securely
user: AuthUser;
accessToken?: string;
token?: string; // Alias for accessToken (deprecated)
expiresIn?: string;
userId?: string;
user?: AuthUser;
}
Comment on lines 38 to 47
Copy link

Copilot AI Apr 11, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The documented AuthResponse interface marks accessToken, token, user, and expiresIn as required, but the SDK’s exported AuthResponse type has these fields optional (accessToken?, deprecated token?, expiresIn?, user?). Please align the docs with the actual SDK typings (or explicitly state which fields are guaranteed by the backend) so TypeScript users don’t get a false sense of strict guarantees.

Copilot uses AI. Check for mistakes.
```

**Example**

```typescript
const { token, user } = await client.auth.login({
const { accessToken, user } = await client.auth.login({
email: 'alice@example.com',
password: 'secret123',
});

console.log(token); // 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...'
console.log(user.name); // 'Alice'
```

<Note>
Store `token` securely — for example in `localStorage` or an HTTP-only cookie — and pass it to authenticated API calls. Never expose it in URLs or logs.
</Note>
---

## `refreshToken`

Rotate the current access token.

- **Browser**: Call without arguments. It will automatically use the `refreshToken` stored in your HTTP-only cookies.
- **Mobile/Node**: Pass the `refreshToken` string manually.

```typescript
refreshToken(refreshToken?: string): Promise<AuthResponse>
```

---

## me
## `me`

Fetch the profile of the currently authenticated user. If you call `login()` first, you do not need to pass a token explicitly — the module uses the stored session token automatically.
Fetch the profile of the currently authenticated user.

```typescript
me(token?: string): Promise<AuthUser>
```

**Parameters**

| Name | Type | Required | Description |
|---|---|---|---|
| `token` | `string` | No | Override the stored session token. |
---

**Returns** `AuthUser`
## `updateProfile`

**Example — using the stored token after login()**
Update the authenticated user's profile fields.

```typescript
await client.auth.login({ email: 'alice@example.com', password: 'secret123' });

const user = await client.auth.me();
console.log(user.email); // 'alice@example.com'
updateProfile(payload: UpdateProfilePayload, token?: string): Promise<{ message: string }>
```

**Example — passing a token directly**
**Example**

```typescript
const token = localStorage.getItem('urbackend_token');
const user = await client.auth.me(token);
await client.auth.updateProfile({ name: 'Alice Smith' });
```

<Note>
Calling `me()` without a token and without a prior `login()` in the same client instance throws an `AuthError`. Always pass the token explicitly if the client is newly initialized (for example, on page reload).
</Note>
---

## `changePassword`

Change the authenticated user's password.

```typescript
changePassword(payload: ChangePasswordPayload, token?: string): Promise<{ message: string }>
```

---

## logout
## Social auth

Clear the locally stored session token. This does not invalidate the token on the server.
urBackend supports OAuth via GitHub and Google.

### `socialStart`

You receive a URL to initiate the OAuth flow. Redirect your user's browser to this URL.

```typescript
socialStart(provider: 'github' | 'google'): string
```

### `socialExchange`

Exchange the `rtCode` received at your callback URL for a refresh token.

```typescript
logout(): void
socialExchange(payload: SocialExchangePayload): Promise<SocialExchangeResponse>
```

**Example**

```typescript
client.auth.logout();
// The stored session token is cleared.
// Subsequent calls to me() will require a token to be passed explicitly.
// At your /auth/callback page
const urlParams = new URLSearchParams(window.location.search);
const rtCode = urlParams.get('rtCode');
const token = new URLSearchParams(window.location.hash.slice(1)).get('token');

Copy link

Copilot AI Apr 11, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the socialExchange example, URLSearchParams.get() returns string | null, but SocialExchangePayload requires string fields. In a typescript code block this is a type error and could also lead to runtime issues if either value is missing. Add a small guard (or explicit non-null assertion with a comment) before calling socialExchange.

Suggested change
if (!rtCode || !token) {
throw new Error('Missing social auth callback parameters');
}

Copilot uses AI. Check for mistakes.
if (!token || !rtCode) {
throw new Error('Missing required OAuth callback parameters');
}

const { refreshToken } = await client.auth.socialExchange({ token, rtCode });
```

---

## Error handling
## Account verification

Use these methods to handle email OTP flows.

| Method | Description |
|---|---|
| `verifyEmail(payload)` | Verify an account using the OTP sent to email. |
| `resendVerificationOtp(payload)` | Request a new verification OTP. |
| `requestPasswordReset(payload)` | Start the "forgot password" flow. |
| `resetPassword(payload)` | Complete password reset using an OTP. |

---

## `publicProfile`

Fetch a public-safe profile for any user by their username. This does not return sensitive fields like email or provider IDs.

```typescript
import urBackend, { AuthError } from '@urbackend/sdk';
publicProfile(username: string): Promise<AuthUser>
```

const client = urBackend({ apiKey: process.env.URBACKEND_API_KEY });
---

try {
await client.auth.login({ email: 'alice@example.com', password: 'wrong' });
} catch (e) {
if (e instanceof AuthError) {
console.error('Login failed:', e.message);
// e.statusCode is 401 or 403
}
}
## `logout`

Call this to revoke your current session on the server and clear the local token.

```typescript
logout(token?: string): Promise<{ success: boolean; message: string }>
```

---

## Manual token management

If you need to manage tokens manually (for example, after social auth), you can use these helper methods:

- `getToken()`: Returns the current in-memory access token.
- `setToken(token)`: Manually set the access token for the client.
Loading
Loading