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

# SDK Introduction

> The official Gately JavaScript SDK for browsers and Node.js

The Gately SDK provides a simple, type-safe way to integrate authentication, user management, and content protection into your applications.

## Features

<CardGroup cols={2}>
  <Card title="Authentication" icon="lock">
    Email/password, social login, and magic links
  </Card>

  <Card title="User Management" icon="user">
    Profiles, sessions, and account management
  </Card>

  <Card title="Page Protection" icon="shield">
    Protect content based on authentication and plans
  </Card>

  <Card title="Email Campaigns" icon="envelope">
    Send campaigns to your members programmatically
  </Card>
</CardGroup>

## Authentication Methods

The SDK supports two authentication methods depending on your environment:

| Environment    | Method     | Key Type                |
| -------------- | ---------- | ----------------------- |
| Browser/Client | Project ID | Public (safe to expose) |
| Server/Node.js | API Key    | Secret (never expose)   |

<Warning>
  **Never expose API keys in client-side code.** Use Project IDs for browser applications and API keys only on the server.
</Warning>

## Quick Start

### Installation

<Tabs>
  <Tab title="NPM">
    ```bash theme={null}
    npm install gately
    ```
  </Tab>

  <Tab title="Yarn">
    ```bash theme={null}
    yarn add gately
    ```
  </Tab>

  <Tab title="CDN">
    ```html theme={null}
    <script 
      src="https://cdn.usegately.com/gately.min.js" 
      data-api-key="YOUR_API_KEY"
      defer
    ></script>
    ```
  </Tab>
</Tabs>

### Browser Usage

For client-side applications, initialize with your API key:

```javascript theme={null}
import { GatelyClient } from 'gately'

// Initialize with API key
const gately = new GatelyClient({
  apiKey: 'gately_pk_live_xxxxxxxx'
})

// Check if user is authenticated
if (gately.isAuthenticated()) {
  const user = gately.getUser()
  console.log('Welcome,', user.email)
}

// Login
const { user, session } = await gately.login('user@example.com', 'password')

// Logout
await gately.logout()
```

### React Usage

```jsx theme={null}
import { GatelyProvider, useGately } from 'gately'

// Wrap your app with the provider
function App() {
  return (
    <GatelyProvider apiKey="gately_pk_live_xxxxxxxx">
      <YourApp />
    </GatelyProvider>
  )
}

// Use in components
function Profile() {
  const { user, isAuthenticated, login, logout } = useGately()
  
  if (!isAuthenticated) {
    return <button onClick={() => login('user@example.com', 'pass')}>Login</button>
  }
  
  return (
    <div>
      <p>Welcome, {user.email}</p>
      <button onClick={logout}>Logout</button>
    </div>
  )
}
```

### Server-Side Usage (Node.js)

For server-side applications, use your secret API key:

```javascript theme={null}
import { GatelyNodeClient } from 'gately/node'

// Initialize with secret API key
const gately = new GatelyNodeClient({
  apiKey: process.env.GATELY_API_KEY // gately_sk_live_xxxxxxxx
})

// Verify user tokens
const user = await gately.verifyToken(token)

// List members
const members = await gately.listMembers()

// Create a member
const member = await gately.createMember({
  email: 'user@example.com',
  full_name: 'John Doe'
})
```

## API Key Types

| Key Type   | Prefix       | Usage               | Security       |
| ---------- | ------------ | ------------------- | -------------- |
| Public Key | `gately_pk_` | Browser/client apps | Safe to expose |
| Secret Key | `gately_sk_` | Server-side only    | Never expose   |

<Info>
  Get your API keys from **Settings → API Keys** in your [Gately dashboard](https://app.usegately.com).
</Info>

## SDK Methods

### Authentication

| Method                              | Description                    |
| ----------------------------------- | ------------------------------ |
| `login(email, password)`            | Login with email and password  |
| `signup(email, password, metadata)` | Create a new account           |
| `loginWithGoogle(options)`          | Login with Google OAuth        |
| `loginWithGithub(options)`          | Login with GitHub OAuth        |
| `sendMagicLink(email, options)`     | Send a passwordless login link |
| `logout()`                          | End the current session        |

### Session Management

| Method                        | Description                           |
| ----------------------------- | ------------------------------------- |
| `isAuthenticated()`           | Check if user is logged in            |
| `getUser()`                   | Get the current user                  |
| `getSession()`                | Get the current session               |
| `fetchSession()`              | Refresh and fetch session from server |
| `onAuthStateChange(callback)` | Listen for auth state changes         |

### User Profile

| Method                         | Description               |
| ------------------------------ | ------------------------- |
| `getUserProfile()`             | Get detailed user profile |
| `updateUserProfile(updates)`   | Update user profile       |
| `changePassword(current, new)` | Change user password      |
| `deleteUserAccount()`          | Delete the user's account |

### Page Protection

| Method                        | Description                          |
| ----------------------------- | ------------------------------------ |
| `initPageProtection(options)` | Initialize automatic page protection |
| `checkAccess(contentId)`      | Check if user can access content     |

## TypeScript Support

The SDK is written in TypeScript and includes full type definitions:

```typescript theme={null}
import { 
  GatelyClient, 
  User, 
  Session, 
  AuthResponse 
} from '@gately/sdk'

const gately = new GatelyClient({
  apiKey: 'gately_pk_live_xxxxxxxx'
})

const handleLogin = async (): Promise<AuthResponse> => {
  return await gately.login('user@example.com', 'password')
}
```

## Configuration Options

```javascript theme={null}
const gately = new GatelyClient({
  // Required: Your API key
  apiKey: 'gately_pk_live_xxxxxxxx',
  
  // Optional: Custom API URL (for self-hosted)
  apiUrl: 'https://api.usegately.com',
  
  // Optional: Auto-refresh sessions before expiry
  autoRefresh: true,
  
  // Optional: Suppress console errors
  suppressConsoleErrors: false
})
```

## Next Steps

<CardGroup cols={2}>
  <Card title="Installation" icon="download" href="/docs/sdk/installation">
    Detailed installation instructions
  </Card>

  <Card title="Authentication" icon="lock" href="/docs/sdk/auth/login.mdx">
    Learn about authentication methods
  </Card>

  <Card title="Page Protection" icon="shield" href="/docs/sdk/protection/overview.mdx">
    Protect your content
  </Card>

  <Card title="API Keys" icon="key" href="/docs/api-reference/api-keys">
    Learn about API key management
  </Card>
</CardGroup>
