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

# Client-Setup

> So erstellst und konfigurierst du den Base44-Client.

<Warning>
  Diese Seite ist Teil eines KI-Coding-Agent-Skills und für Agenten geschrieben, nicht für Menschen. Für die menschenlesbare Base44-Dokumentation siehe die [Entwicklerdokumentation](/developers).
</Warning>

# Client-Setup

So erstellst und konfigurierst du den Base44-Client.

## Inhalt

* [In Base44-generierten Apps](#in-base44-generierten-apps)
* [In externen Apps](#in-externen-apps)
* [In Backend-Funktionen](#in-backend-funktionen)
* [Authentifizierungsmodi](#authentifizierungsmodi) (Anonym, Nutzer, Service-Rolle)
* [Verfügbare Module](#verfügbare-module)
* [Client-Methoden](#client-methoden)
* [Client-Konfigurationsoptionen](#client-konfigurationsoptionen)

## In Base44-generierten Apps

In einer Base44-App wird der Client automatisch erstellt und konfiguriert. Importiere ihn aus `@/api/base44Client` und verwende ihn als `base44`:

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

## In externen Apps

Wenn du Base44 als Backend aus einer externen App nutzt, installiere das SDK und erstelle einen Client direkt mit `createClient()`:

```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);
    }
  }
});
```

**Häufige Fehler:**

* ❌ `createClient({ clientId: "..." })` — FALSCHER Parametername
* ❌ `createClient({ id: "..." })` — FALSCHER Parametername
* ❌ `createClient({ appId: "...", onError: ... })` — FALSCH: onError muss in options sein
* ✅ `createClient({ appId: "..." })` — RICHTIGER Parametername
* ✅ `createClient({ appId: "...", options: { onError: ... } })` — RICHTIG: onError in options

## In Backend-Funktionen

`createClientFromRequest()` ist für Base44-gehostete Backend-Funktionen gedacht. Es extrahiert die Auth aus Request-Headern, die Base44 injiziert, und gibt einen Client zurück, der Service-Rollen-Zugriff enthält (`base44.asServiceRole`). Für Frontends und externe Backends verwende stattdessen `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 });
});
```

## Authentifizierungsmodi

| Modus             | Wie erhalten                                                       | Berechtigungen           |
| ----------------- | ------------------------------------------------------------------ | ------------------------ |
| **Anonym**        | `createClient({ appId })` ohne Token                               | Nur öffentliche Daten    |
| **Nutzer**        | Nach `loginViaEmailPassword()` oder über `createClientFromRequest` | Eigene Daten des Nutzers |
| **Service-Rolle** | `base44.asServiceRole.*` im Backend                                | Voller Admin-Zugriff     |

## Anonymer Modus

Keine Authentifizierung. Kann nur auf öffentliche Ressourcen zugreifen.

```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();
```

## Nutzer-Modus

Nach der Anmeldung enthält der Client automatisch den 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
```

## Service-Rollen-Modus

Admin-Zugriff. **Nur 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 });
});
```

## Verfügbare Module

Der Client stellt diese Module bereit:

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

## Client-Methoden

Der Client stellt diese Methoden bereit:

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

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

### setToken

Aktualisiert den Authentifizierungstoken für alle nachfolgenden API-Anfragen und WebSocket-Verbindungen.

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

### cleanup

Trennt WebSocket-Verbindungen. Rufe das auf, wenn du mit dem Client fertig bist oder die Komponente unmountet wird.

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

## Client-Konfigurationsoptionen

```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)
  }
});
```

**⚠️ Kritisch:**

* Der Parametername ist `appId`, nicht `clientId` oder `id`. Ein falscher Parametername führt zu Fehlern.
* Der `onError`-Handler muss im `options`-Objekt verschachtelt sein, nicht auf oberster Ebene.

## Type Definitions

### 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>Diese Seite wurde mit KI übersetzt. Für die genauesten und aktuellsten Informationen siehe die [englische Version](/). </Note>
