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

# Configuração do cliente

> Como criar e configurar o cliente Base44.

<Warning>
  Esta página faz parte de uma habilidade de agente de código IA e é escrita para agentes, não para humanos. Para a documentação legível por humanos da Base44, veja a [documentação para desenvolvedores](/developers).
</Warning>

# Configuração do cliente

Como criar e configurar o cliente Base44.

## Conteúdo

* [Em aplicativos gerados pela Base44](#in-base44-generated-apps)
* [Em aplicativos externos](#in-external-apps)
* [Em funções de backend](#in-backend-functions)
* [Modos de autenticação](#authentication-modes) (Anônimo, Usuário, Service Role)
* [Módulos disponíveis](#available-modules)
* [Métodos do cliente](#client-methods)
* [Opções de configuração do cliente](#client-configuration-options)

## Em aplicativos gerados pela Base44

Dentro de um aplicativo Base44, o cliente é criado e configurado automaticamente. Importe-o de `@/api/base44Client` e use-o como `base44`:

```javascript theme={null}
const tasks = await base44.entities.Task.list();
```

## Em aplicativos externos

Ao usar a Base44 como backend de um aplicativo externo, instale o SDK e crie um cliente chamando `createClient()` diretamente:

```bash theme={null}
npm install @base44/sdk
```

```javascript theme={null}
import { createClient } from "@base44/sdk";

// IMPORTANT: The parameter name is 'appId' (NOT 'clientId', NOT 'id')
// IMPORTANT: onError must be nested inside 'options' object
const base44 = createClient({
  appId: "your-app-id",          // Required: Use 'appId' parameter
  token: "optional-user-token",  // Optional: for pre-authenticated requests
  options: {                      // Optional: configuration options
    onError: (error) => {         // Optional: error handler (must be in options)
      console.error("Base44 error:", error);
    }
  }
});
```

**Erros comuns:**

* ❌ `createClient({ clientId: "..." })` - Nome de parâmetro ERRADO
* ❌ `createClient({ id: "..." })` - Nome de parâmetro ERRADO
* ❌ `createClient({ appId: "...", onError: ... })` - ERRADO: onError deve estar em options
* ✅ `createClient({ appId: "..." })` - Nome de parâmetro CORRETO
* ✅ `createClient({ appId: "...", options: { onError: ... } })` - CORRETO: onError em options

## Em funções de backend

`createClientFromRequest()` é projetado para funções de backend hospedadas na Base44. Ele extrai autenticação dos cabeçalhos de solicitação que a Base44 injeta e retorna um cliente que inclui acesso service role (`base44.asServiceRole`). Para frontends e backends externos, use `createClient()`.

```javascript theme={null}
import { createClientFromRequest } from "@base44/sdk";

Deno.serve(async (req) => {
  const base44 = createClientFromRequest(req);
  
  // Client inherits authentication from the request
  const user = await base44.auth.me();
  
  return Response.json({ user });
});
```

## Modos de autenticação

| Modo             | Como obter                                                      | Permissões                    |
| ---------------- | --------------------------------------------------------------- | ----------------------------- |
| **Anônimo**      | `createClient({ appId })` sem token                             | Apenas dados públicos         |
| **Usuário**      | Após `loginViaEmailPassword()` ou via `createClientFromRequest` | Dados próprios do usuário     |
| **Service Role** | `base44.asServiceRole.*` no backend                             | Acesso total de administrador |

## Modo anônimo

Sem autenticação. Só pode acessar recursos públicos.

```javascript theme={null}
const base44 = createClient({ appId: "your-app-id" });

// Only works if Task entity allows anonymous read
const publicTasks = await base44.entities.Task.list();
```

## Modo de usuário

Depois que o usuário faz login, o cliente inclui automaticamente seu token.

```javascript theme={null}
const base44 = createClient({ appId: "your-app-id" });

// Login sets the token
await base44.auth.loginViaEmailPassword("user@example.com", "password");

// Subsequent requests are authenticated
const user = await base44.auth.me();
const myTasks = await base44.entities.Task.list();  // filtered by permissions
```

## Modo Service Role

Acesso em nível de administrador. **Apenas backend.**

```javascript theme={null}
// Inside a backend function
Deno.serve(async (req) => {
  const base44 = createClientFromRequest(req);
  
  // User mode - respects permissions
  const myTasks = await base44.entities.Task.list();
  
  // Service role - bypasses permissions
  const allTasks = await base44.asServiceRole.entities.Task.list();
  const allUsers = await base44.asServiceRole.entities.User.list();
  const oauthToken = await base44.asServiceRole.connectors.getAccessToken("slack");
  
  return Response.json({ myTasks, allTasks });
});
```

## Módulos disponíveis

O cliente expõe estes módulos:

```javascript theme={null}
base44.agents        // AI conversations
base44.analytics     // Event tracking
base44.appLogs       // App usage logging
base44.auth          // Authentication
base44.connectors    // Per-user OAuth flows (UserConnectorsModule)
base44.entities      // CRUD operations
base44.functions     // Backend function invocation
base44.integrations  // Third-party services
base44.users         // User invitations

// Service role only (backend)
base44.asServiceRole.agents
base44.asServiceRole.appLogs
base44.asServiceRole.connectors  // App-scoped OAuth tokens (ConnectorsModule)
base44.asServiceRole.entities
base44.asServiceRole.functions
base44.asServiceRole.integrations
base44.asServiceRole.sso         // SSO token generation
```

## Métodos do cliente

O cliente fornece estes métodos:

```javascript theme={null}
// Set authentication token for all subsequent requests
base44.setToken(newToken);

// Cleanup WebSocket connections (call when done with client)
base44.cleanup();
```

### setToken

Atualiza o token de autenticação para todas as solicitações de API e conexões WebSocket subsequentes.

```javascript theme={null}
// After receiving a token (e.g., from external auth)
base44.setToken("new-jwt-token");
```

### cleanup

Desconecta conexões WebSocket. Chame quando você terminou com o cliente ou quando o componente for desmontado.

```javascript theme={null}
// Cleanup on component unmount (React example)
useEffect(() => {
  return () => base44.cleanup();
}, []);
```

## Opções de configuração do cliente

```javascript theme={null}
createClient({
  appId: "your-app-id",      // Required: MUST use 'appId' (not 'clientId' or 'id')
  token: "jwt-token",        // Optional: pre-set auth token
  options: {                 // Optional: configuration options
    onError: (error) => {}   // Optional: global error handler (must be in options)
  }
});
```

**⚠️ Crítico:**

* O nome do parâmetro é `appId`, não `clientId` ou `id`. Usar o nome do parâmetro errado causará erros.
* O manipulador `onError` deve estar aninhado dentro do objeto `options`, não no nível superior.

## Definições de tipo

### CreateClientConfig

```typescript theme={null}
/** Configuration for creating a Base44 client. */
interface CreateClientConfig {
  /** The Base44 app ID (required). */
  appId: string;
  /** User authentication token. Used to authenticate as a specific user. */
  token?: string;
  /** @internal Service role token; only set automatically in Base44-hosted backend functions. */
  serviceToken?: string;
  /** Additional client options. */
  options?: CreateClientOptions;
}

/** Options for creating a Base44 client. */
interface CreateClientOptions {
  /** Optional error handler called whenever an API error occurs. */
  onError?: (error: Error) => void;
}
```

### Base44Client

```typescript theme={null}
/** The Base44 client instance. */
interface Base44Client {
  /** Agents module for managing AI agent conversations. */
  agents: AgentsModule;
  /** Analytics module for tracking custom events. */
  analytics: AnalyticsModule;
  /** App logs module for tracking app usage. */
  appLogs: AppLogsModule;
  /** Auth module for user authentication and management. */
  auth: AuthModule;
  /** Entities module for CRUD operations on your data models. */
  entities: EntitiesModule;
  /** Functions module for invoking custom backend functions. */
  functions: FunctionsModule;
  /** Integrations module for calling pre-built integration methods. */
  integrations: IntegrationsModule;

  /** Cleanup function to disconnect WebSocket connections. */
  cleanup(): void;

  /** Sets a new authentication token for all subsequent requests. */
  setToken(newToken: string): void;

  /** Per-user OAuth flows. Each end user has their own connection. */
  connectors: UserConnectorsModule;

  /** Provides access to modules with elevated service role permissions (backend only). */
  readonly asServiceRole: {
    agents: AgentsModule;
    appLogs: AppLogsModule;
    /** App-scoped OAuth tokens. All users share the same connected account. */
    connectors: ConnectorsModule;
    entities: EntitiesModule;
    functions: FunctionsModule;
    integrations: IntegrationsModule;
    /** SSO token generation for users. */
    sso: SsoModule;
    cleanup(): void;
  };
}
```

<Note>Esta página foi traduzida usando IA. Para informações mais precisas e atualizadas, consulte a [versão em inglês](/). </Note>
