> ## Documentation Index
> Fetch the complete documentation index at: https://usegately.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# React SDK

> Official React SDK for Gately - hooks-based authentication with reactive state management

The **@gately/react** SDK provides production-ready authentication for React applications with a hooks-based API and automatic state management.

<Info>
  **Version:** @gately/react\@2.2.0\
  **Features:** `useGately` hook, `GatelyProvider` context, TypeScript support, SSR support
</Info>

## Installation

```bash theme={null}
npm install @gately/react@latest
```

Or install a specific version:

```bash theme={null}
npm install @gately/react@2.2.0
```

Get your API key: **[Dashboard → Settings → API Keys](https://www.usegately.com/dashboard?settings=api)**

## Quick Start

```tsx theme={null}
import { GatelyProvider, useGately } from '@gately/react'

function App() {
  return (
    <GatelyProvider apiKey={process.env.REACT_APP_GATELY_API_KEY}>
      <Dashboard />
    </GatelyProvider>
  )
}

function Dashboard() {
  const { user, isAuthenticated, logout } = useGately()

  if (!isAuthenticated) return <LoginForm />

  return (
    <div>
      <h1>Welcome, {user?.email}!</h1>
      <button onClick={logout}>Logout</button>
    </div>
  )
}
```

## GatelyProvider

Wraps your app to provide authentication context. Must be a parent of any component using `useGately`.

```tsx theme={null}
import { GatelyProvider } from '@gately/react'

<GatelyProvider
  apiKey={process.env.REACT_APP_GATELY_API_KEY}
  apiUrl="https://api.usegately.com"   // optional
  autoRefresh={true}                    // optional, default: true
>
  <App />
</GatelyProvider>
```

| Prop          | Type      | Required | Description                             |
| ------------- | --------- | -------- | --------------------------------------- |
| `apiKey`      | `string`  | ✅        | Your Gately API key                     |
| `apiUrl`      | `string`  | No       | Custom API URL                          |
| `autoRefresh` | `boolean` | No       | Auto-refresh sessions (default: `true`) |

## useGately Hook

The main hook — provides all auth state and methods.

```tsx theme={null}
const {
  // State
  user,
  session,
  isAuthenticated,
  isLoading,
  error,

  // Auth methods
  login,
  signup,
  logout,
  sendMagicLink,
  resetPassword,

  // User methods
  getUserProfile,
  updateUserProfile,
  changePassword,
  deleteUserAccount,

  // Session
  fetchSession,
  client
} = useGately()
```

### State

| Property          | Type              | Description                       |
| ----------------- | ----------------- | --------------------------------- |
| `user`            | `User \| null`    | Currently authenticated user      |
| `session`         | `Session \| null` | Current session                   |
| `isAuthenticated` | `boolean`         | Whether user is logged in         |
| `isLoading`       | `boolean`         | Loading state for auth operations |
| `error`           | `Error \| null`   | Error from last operation         |

### Methods

| Method              | Signature                                 | Description                 |
| ------------------- | ----------------------------------------- | --------------------------- |
| `login`             | `(email, password) => Promise`            | Login with email/password   |
| `signup`            | `(email, password, metadata?) => Promise` | Create a new account        |
| `logout`            | `() => Promise<void>`                     | End current session         |
| `sendMagicLink`     | `(email, redirectTo?) => Promise<void>`   | Send passwordless link      |
| `resetPassword`     | `(email) => Promise<void>`                | Send password reset email   |
| `getUserProfile`    | `() => Promise`                           | Fetch full user profile     |
| `updateUserProfile` | `(updates) => Promise`                    | Update user profile         |
| `changePassword`    | `(current, new) => Promise<void>`         | Change password             |
| `deleteUserAccount` | `() => Promise<void>`                     | Delete account              |
| `fetchSession`      | `() => Promise<Session \| null>`          | Refresh session from server |

## Authentication Examples

### Login Form

```tsx theme={null}
import { useGately } from '@gately/react'
import { useState } from 'react'

function LoginForm() {
  const { login, isLoading, error } = useGately()
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    try {
      await login(email, password)
      // redirect or update UI
    } catch (err) {
      // error is also available via the hook's error property
    }
  }

  return (
    <form onSubmit={handleSubmit}>
      <input type="email" value={email} onChange={e => setEmail(e.target.value)} />
      <input type="password" value={password} onChange={e => setPassword(e.target.value)} />
      <button type="submit" disabled={isLoading}>
        {isLoading ? 'Signing in...' : 'Sign In'}
      </button>
      {error && <p className="error">{error.message}</p>}
    </form>
  )
}
```

### Sign Up

```tsx theme={null}
function SignupForm() {
  const { signup, isLoading, error } = useGately()

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    await signup(email, password, { name: 'Jane Doe' })
  }

  // ...
}
```

### Magic Link

```tsx theme={null}
function MagicLinkForm() {
  const { sendMagicLink, isLoading } = useGately()
  const [sent, setSent] = useState(false)

  const handleSend = async (email: string) => {
    await sendMagicLink(email)
    setSent(true)
  }

  return sent
    ? <p>Check your email!</p>
    : <button onClick={() => handleSend('user@example.com')} disabled={isLoading}>
        Send Magic Link
      </button>
}
```

## Route Protection

### With React Router

```tsx theme={null}
import { useGately } from '@gately/react'
import { Navigate } from 'react-router-dom'

function ProtectedRoute({ children }: { children: React.ReactNode }) {
  const { isAuthenticated, isLoading } = useGately()

  if (isLoading) return <div>Loading...</div>
  if (!isAuthenticated) return <Navigate to="/login" replace />

  return <>{children}</>
}

// Usage
<Routes>
  <Route path="/login" element={<LoginPage />} />
  <Route
    path="/dashboard"
    element={
      <ProtectedRoute>
        <Dashboard />
      </ProtectedRoute>
    }
  />
</Routes>
```

## User Profile

```tsx theme={null}
function ProfilePage() {
  const { user, updateUserProfile, isLoading } = useGately()
  const [name, setName] = useState(user?.name ?? '')

  const handleSave = async () => {
    await updateUserProfile({ name })
  }

  return (
    <div>
      <p>{user?.email}</p>
      <input value={name} onChange={e => setName(e.target.value)} />
      <button onClick={handleSave} disabled={isLoading}>Save</button>
    </div>
  )
}
```

## Other Hooks

### useAuth

Returns the full auth context (same as `useGately`):

```tsx theme={null}
import { useAuth } from '@gately/react'

const { login, logout, isAuthenticated } = useAuth()
```

### useUser

Focused hook for user profile data:

```tsx theme={null}
import { useUser } from '@gately/react'

const { user, profile, isLoading, refetch, update } = useUser()
```

### useProtected

Simple auth status check:

```tsx theme={null}
import { useProtected } from '@gately/react'

const { isAuthenticated, isLoading, user } = useProtected()
```

## TypeScript

```typescript theme={null}
import type { User, Session, GatelyContextValue } from '@gately/react'

const handleUser = (user: User) => {
  console.log(user.id, user.email, user.name)
}
```

## Testing

```tsx theme={null}
jest.mock('@gately/react', () => ({
  ...jest.requireActual('@gately/react'),
  useGately: () => ({
    user: { id: '1', email: 'test@example.com' },
    isAuthenticated: true,
    isLoading: false,
    error: null,
    logout: jest.fn()
  })
}))
```

## Next Steps

<CardGroup cols={2}>
  <Card title="Next.js SDK" icon="nextjs" href="/docs/sdk/nextjs">
    Add server-side auth and middleware
  </Card>

  <Card title="Node.js SDK" icon="server" href="/docs/sdk/nodejs">
    Backend token verification
  </Card>
</CardGroup>

**Support:** [support@usegately.com](mailto:support@usegately.com) · [Slack Community](https://join.slack.com/t/usegately/shared_invite/zt-3llscjz41-PuVEY5Xu0M2DCi8WEojN0Q)
