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

# Configurazione del client

> Come creare e configurare il client Base44.

<Warning>
  Questa pagina fa parte di una skill per agenti di codifica IA ed è scritta per gli agenti, non per gli esseri umani. Per la documentazione Base44 leggibile dagli umani, consulta la [documentazione per sviluppatori](/developers).
</Warning>

# Configurazione del client

Come creare e configurare il client Base44.

## Contenuti

* [Nelle app generate da Base44](#nelle-app-generate-da-base44)
* [Nelle app esterne](#nelle-app-esterne)
* [Nelle funzioni backend](#nelle-funzioni-backend)
* [Modalità di autenticazione](#modalità-di-autenticazione) (Anonima, Utente, Ruolo di servizio)
* [Moduli disponibili](#moduli-disponibili)
* [Metodi del client](#metodi-del-client)
* [Opzioni di configurazione del client](#opzioni-di-configurazione-del-client)

## Nelle app generate da Base44

All'interno di un'app Base44, il client viene creato e configurato automaticamente. Importalo da `@/api/base44Client` e usalo come `base44`:

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

## Nelle app esterne

Quando usi Base44 come backend da un'app esterna, installa l'SDK e crea un client chiamando `createClient()` direttamente:

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

**Errori comuni:**

* ❌ `createClient({ clientId: "..." })` - Nome del parametro SBAGLIATO
* ❌ `createClient({ id: "..." })` - Nome del parametro SBAGLIATO
* ❌ `createClient({ appId: "...", onError: ... })` - SBAGLIATO: onError deve essere in options
* ✅ `createClient({ appId: "..." })` - Nome del parametro CORRETTO
* ✅ `createClient({ appId: "...", options: { onError: ... } })` - CORRETTO: onError in options

## Nelle funzioni backend

`createClientFromRequest()` è progettato per le funzioni backend ospitate da Base44. Estrae l'autenticazione dagli header della richiesta che Base44 inserisce e restituisce un client che include l'accesso con ruolo di servizio (`base44.asServiceRole`). Per frontend e backend esterni, usa invece `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 });
});
```

## Modalità di autenticazione

| Modalità              | Come ottenerla                                                     | Permessi               |
| --------------------- | ------------------------------------------------------------------ | ---------------------- |
| **Anonima**           | `createClient({ appId })` senza token                              | Solo dati pubblici     |
| **Utente**            | Dopo `loginViaEmailPassword()` o tramite `createClientFromRequest` | Dati dell'utente       |
| **Ruolo di servizio** | `base44.asServiceRole.*` nel backend                               | Accesso admin completo |

## Modalità anonima

Nessuna autenticazione. Può accedere solo alle risorse pubbliche.

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

## Modalità utente

Dopo che l'utente ha effettuato l'accesso, il client include automaticamente il suo 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
```

## Modalità ruolo di servizio

Accesso a livello admin. **Solo 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 });
});
```

## Moduli disponibili

Il client espone questi moduli:

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

## Metodi del client

Il client fornisce questi metodi:

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

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

### setToken

Aggiorna il token di autenticazione per tutte le richieste API successive e le connessioni WebSocket.

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

### cleanup

Disconnette le connessioni WebSocket. Chiamalo quando hai finito con il client o quando il componente si smonta.

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

## Opzioni di configurazione del client

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

**⚠️ Critico:**

* Il nome del parametro è `appId`, non `clientId` o `id`. Usare il nome sbagliato causerà errori.
* Il gestore `onError` deve essere annidato all'interno dell'oggetto `options`, non al livello superiore.

## Definizioni di 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>Questa pagina è stata tradotta utilizzando l'IA. Per informazioni più accurate e aggiornate, consulta la [versione inglese](/). </Note>
