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

# Base44 Coder

> Costruisci app sulla piattaforma Base44 usando l'SDK JavaScript di 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>

# Base44 Coder

Costruisci app sulla piattaforma Base44 usando l'SDK JavaScript di Base44.

## ⚡ AZIONE IMMEDIATA RICHIESTA - Leggi prima questo

Questa skill si attiva su QUALSIASI menzione di "base44" o quando esiste una cartella `base44/`. **NON leggere file di documentazione né cercare sul web prima di agire.**

**La tua prima azione DEVE essere:**

1. Controllare se `base44/config.jsonc` esiste nella directory corrente
2. Se **SÌ** (scenario progetto esistente):
   * Questa skill (base44-sdk) gestisce la richiesta
   * Implementa le funzionalità usando l'SDK di Base44
   * NON usare base44-cli a meno che l'utente non richieda esplicitamente comandi CLI
3. Se **NO** (scenario nuovo progetto):
   * Passa alla skill base44-cli per l'inizializzazione del progetto
   * Questa skill non può aiutare finché il progetto non è inizializzato

## Quando usare questa skill vs base44-cli

**Usa base44-sdk quando:**

* Costruisci funzionalità in un progetto Base44 **ESISTENTE**
* `base44/config.jsonc` esiste già nel progetto
* Sono presenti import dell'SDK Base44 (`@base44/sdk`)
* Scrivi codice JavaScript/TypeScript usando i moduli SDK di Base44
* Implementi funzionalità, componenti o feature
* L'utente menziona: "implementa", "costruisci una feature", "aggiungi funzionalità", "scrivi codice per"
* L'utente dice "crea un'app \[tipo]" **e** un progetto Base44 esiste già

**NON USARE base44-sdk per:**

* ❌ Inizializzare nuovi progetti Base44 (usa `base44-cli` invece)
* ❌ Directory vuote senza configurazione Base44
* ❌ Quando l'utente dice "crea un nuovo progetto/app/sito Base44" e non esiste alcun progetto
* ❌ Comandi CLI come `npx base44 create`, `npx base44 deploy`, `npx base44 login` (usa `base44-cli`)

**Dipendenze delle skill:**

* `base44-sdk` presuppone che un progetto Base44 sia **già inizializzato**
* `base44-cli` è un **prerequisito** per `base44-sdk` nei nuovi progetti
* Se l'utente vuole "creare un'app" e non esiste alcun progetto Base44, usa prima `base44-cli`

**Logica di controllo dello stato:**
Prima di selezionare questa skill, verifica:

* SE (l'utente menziona "crea/costruisci app" OPPURE "crea un progetto"):
  * SE (la directory è vuota OPPURE non esiste `base44/config.jsonc`):
    → Usa **base44-cli** (serve inizializzazione del progetto)
  * ALTRIMENTI:
    → Usa **base44-sdk** (progetto esistente, costruisci feature)

## Avvio rapido

```javascript theme={null}
// In Base44-generated apps, base44 client is pre-configured and available

// CRUD operations
const task = await base44.entities.Task.create({ title: "New task", status: "pending" });
const tasks = await base44.entities.Task.list();
await base44.entities.Task.update(task.id, { status: "done" });

// Get current user
const user = await base44.auth.me();
```

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

// IMPORTANT: Use 'appId' (NOT 'clientId' or 'id')
const base44 = createClient({ appId: "your-app-id" });
await base44.auth.loginViaEmailPassword("user@example.com", "password");
```

## ⚠️ CRITICO: non inventare API

**Prima di scrivere QUALSIASI codice Base44, verifica i nomi dei metodi rispetto a questa tabella o a [QUICK\_REFERENCE.md](https://docs.base44.com/developers/skills/base44-sdk/references/QUICK_REFERENCE.md).**

L'SDK di Base44 ha nomi di metodo unici. NON assumere pattern da Firebase, Supabase o altri SDK.

### Autenticazione - SBAGLIATO vs CORRETTO

| ❌ SBAGLIATO (inventato)                 | ✅ CORRETTO                                    |
| --------------------------------------- | --------------------------------------------- |
| `signInWithGoogle()`                    | `loginWithProvider('google')`                 |
| `signInWithProvider('google')`          | `loginWithProvider('google')`                 |
| `auth.google()`                         | `loginWithProvider('google')`                 |
| `signInWithEmailAndPassword(email, pw)` | `loginViaEmailPassword(email, pw)`            |
| `signIn(email, pw)`                     | `loginViaEmailPassword(email, pw)`            |
| `createUser()` / `signUp()`             | `register({email, password})`                 |
| `onAuthStateChanged()`                  | `me()` (nessun listener, chiama quando serve) |
| `currentUser`                           | `await auth.me()`                             |

### Funzioni - SBAGLIATO vs CORRETTO

| ❌ SBAGLIATO (inventato)        | ✅ CORRETTO                       |
| ------------------------------ | -------------------------------- |
| `functions.call('name', data)` | `functions.invoke('name', data)` |
| `functions.run('name', data)`  | `functions.invoke('name', data)` |
| `callFunction('name', data)`   | `functions.invoke('name', data)` |
| `httpsCallable('name')(data)`  | `functions.invoke('name', data)` |

### Integrazioni - SBAGLIATO vs CORRETTO

| ❌ SBAGLIATO (inventato)        | ✅ CORRETTO                                         |
| ------------------------------ | -------------------------------------------------- |
| `ai.generate(prompt)`          | `integrations.Core.InvokeLLM({prompt})`            |
| `openai.chat(prompt)`          | `integrations.Core.InvokeLLM({prompt})`            |
| `llm(prompt)`                  | `integrations.Core.InvokeLLM({prompt})`            |
| `sendEmail(to, subject, body)` | `integrations.Core.SendEmail({to, subject, body})` |
| `email.send()`                 | `integrations.Core.SendEmail({to, subject, body})` |
| `uploadFile(file)`             | `integrations.Core.UploadFile({file})`             |
| `storage.upload(file)`         | `integrations.Core.UploadFile({file})`             |

### Entità - SBAGLIATO vs CORRETTO

| ❌ SBAGLIATO (inventato)      | ✅ CORRETTO                    |
| ---------------------------- | ----------------------------- |
| `entities.Task.find({...})`  | `entities.Task.filter({...})` |
| `entities.Task.findOne(id)`  | `entities.Task.get(id)`       |
| `entities.Task.insert(data)` | `entities.Task.create(data)`  |
| `entities.Task.remove(id)`   | `entities.Task.delete(id)`    |
| `entities.Task.onChange(cb)` | `entities.Task.subscribe(cb)` |

## Moduli SDK

| Modulo                     | Scopo                                                   | Riferimento                                                                                          |
| -------------------------- | ------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
| `entities`                 | Operazioni CRUD sui modelli di dati                     | [entities.md](https://docs.base44.com/developers/skills/base44-sdk/references/entities.md)           |
| `auth`                     | Login, registrazione, gestione utenti                   | [auth.md](https://docs.base44.com/developers/skills/base44-sdk/references/auth.md)                   |
| `agents`                   | Conversazioni e messaggi IA                             | [base44-agents.md](https://docs.base44.com/developers/skills/base44-sdk/references/base44-agents.md) |
| `functions`                | Invocazione di funzioni backend                         | [functions.md](https://docs.base44.com/developers/skills/base44-sdk/references/functions.md)         |
| `integrations`             | IA, email, upload file, API personalizzate              | [integrations.md](https://docs.base44.com/developers/skills/base44-sdk/references/integrations.md)   |
| `analytics`                | Traccia eventi personalizzati e attività utente         | [analytics.md](https://docs.base44.com/developers/skills/base44-sdk/references/analytics.md)         |
| `appLogs`                  | Registra l'attività degli utenti nell'app               | [app-logs.md](https://docs.base44.com/developers/skills/base44-sdk/references/app-logs.md)           |
| `users`                    | Invita utenti all'app                                   | [users.md](https://docs.base44.com/developers/skills/base44-sdk/references/users.md)                 |
| `asServiceRole.connectors` | Token OAuth con scope dell'app (solo ruolo di servizio) | [connectors.md](https://docs.base44.com/developers/skills/base44-sdk/references/connectors.md)       |
| `asServiceRole.sso`        | Generazione di token SSO (solo ruolo di servizio)       | [sso.md](https://docs.base44.com/developers/skills/base44-sdk/references/sso.md)                     |

Per la configurazione del client e le modalità di autenticazione, consulta [client.md](https://docs.base44.com/developers/skills/base44-sdk/references/client.md).

### TypeScript e registri di tipo

Ogni file di riferimento include una sezione "Type Definitions" con interfacce e tipi TypeScript per i metodi, i parametri e i valori di ritorno del modulo.

**Ottenere entità, funzioni e agenti tipizzati:** la CLI di Base44 genera i tipi dalle risorse del tuo progetto (entità, funzioni, agenti), incluse le estensioni a `EntityTypeRegistry`, `FunctionNameRegistry` e `AgentNameRegistry`, e li collega al tuo progetto in modo da ottenere autocompletamento e controllo dei tipi senza configurazione manuale. Per come generare i tipi, usa la skill **base44-cli**.

**Estensione manuale:** puoi invece estendere i registri da solo in un file `.d.ts`; consulta le sezioni Type Definitions in [entities.md](https://docs.base44.com/developers/skills/base44-sdk/references/entities.md), [functions.md](https://docs.base44.com/developers/skills/base44-sdk/references/functions.md) e [base44-agents.md](https://docs.base44.com/developers/skills/base44-sdk/references/base44-agents.md).

## Installazione

Installa l'SDK di Base44:

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

**Importante:** non assumere o codificare in modo fisso la versione del pacchetto `@base44/sdk`. Installa sempre senza specificatore di versione per ottenere l'ultima versione.

## Creazione di un client (app esterne)

Quando crei un client in app esterne, **usa SEMPRE `appId` come nome del parametro**:

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

// ✅ CORRECT
const base44 = createClient({ appId: "your-app-id" });

// ❌ WRONG - Do NOT use these:
// const base44 = createClient({ clientId: "your-app-id" });  // WRONG
// const base44 = createClient({ id: "your-app-id" });        // WRONG
```

**Parametro richiesto:** `appId` (stringa) - L'ID dell'applicazione Base44

**Parametri opzionali:**

* `token` (stringa) - Token utente pre-autenticato
* `options` (oggetto) - Opzioni di configurazione
  * `options.onError` (funzione) - Gestore di errori globale

**Esempio con gestore di errori:**

```javascript theme={null}
const base44 = createClient({
  appId: "your-app-id",
  options: {
    onError: (error) => {
      console.error("Base44 error:", error);
    }
  }
});
```

## Selezione del modulo

**Lavori con i dati dell'app?**

* Crea/leggi/aggiorna/elimina record → `entities`
* Importa dati da file → `entities.importEntities()`
* Aggiornamenti in tempo reale → `entities.EntityName.subscribe()`

**Gestione utenti?**

* Login/registrazione/logout → `auth`
* Ottieni l'utente corrente → `auth.me()`
* Aggiorna il profilo utente → `auth.updateMe()`
* Invita utenti → `users.inviteUser()`

**Funzionalità IA?**

* Chatta con agenti IA → `agents` (richiede un utente loggato)
* Crea una nuova conversazione → `agents.createConversation()`
* Gestisci conversazioni → `agents.getConversations()`
* Genera testo/JSON con l'IA → `integrations.Core.InvokeLLM()`
* Genera immagini → `integrations.Core.GenerateImage()`

**Logica di backend personalizzata?**

* Esegui codice lato server → `functions.invoke()`
* Serve accesso admin → `base44.asServiceRole.functions.invoke()`

**Servizi esterni?**

* Invia email → `integrations.Core.SendEmail()`
* Carica file → `integrations.Core.UploadFile()`
* API personalizzate → `integrations.custom.call()`
* OAuth con scope dell'app (account del costruttore dell'app) → `asServiceRole.connectors.getConnection()` (solo backend)

**Tracciamento e analytics?**

* Traccia eventi personalizzati → `analytics.track()`
* Registra visualizzazioni di pagina/attività → `appLogs.logUserInApp()`

## Pattern comuni

### Filtra e ordina i dati

```javascript theme={null}
const pendingTasks = await base44.entities.Task.filter(
  { status: "pending", assignedTo: userId },  // query
  "-created_date",                             // sort (descending)
  10,                                          // limit
  0                                            // skip
);
```

### Route protette (verifica autenticazione)

```javascript theme={null}
const user = await base44.auth.me();
if (!user) {
  // Navigate to your custom login page
  navigate('/login', { state: { returnTo: window.location.pathname } });
  return;
}
```

### Chiamata a funzione backend

```javascript theme={null}
// Frontend
// ⚠️ invoke() returns the RAW axios response — your function's JSON is on `.data`,
//    NOT the top-level object. It also THROWS on non-2xx (error body at err.response.data).
const res = await base44.functions.invoke("processOrder", {
  orderId: "123",
  action: "ship"
});
const result = res.data; // ✅ e.g. res.data.success  (res itself is { data, status, headers, … })

// Backend function (Deno)
import { createClientFromRequest } from "npm:@base44/sdk";

Deno.serve(async (req) => {
  const base44 = createClientFromRequest(req);
  const { orderId, action } = await req.json();
  // Process with service role for admin access
  const order = await base44.asServiceRole.entities.Orders.get(orderId);
  return Response.json({ success: true });
});
```

### Accesso con ruolo di servizio

Usa `asServiceRole` nelle funzioni backend per operazioni di livello admin:

```javascript theme={null}
// User mode - respects permissions
const myTasks = await base44.entities.Task.list();

// Service role - full access (backend only)
const allTasks = await base44.asServiceRole.entities.Task.list();
const token = await base44.asServiceRole.connectors.getAccessToken("slack");
```

## Frontend vs Backend

| Capacità                                    | Frontend | Backend |
| ------------------------------------------- | -------- | ------- |
| `entities` (dati dell'utente)               | Sì       | Sì      |
| `auth`                                      | Sì       | Sì      |
| `agents`                                    | Sì       | Sì      |
| `functions.invoke()`                        | Sì       | Sì      |
| `functions.fetch()`                         | Sì       | Sì      |
| `integrations`                              | Sì       | Sì      |
| `analytics`                                 | Sì       | Sì      |
| `appLogs`                                   | Sì       | Sì      |
| `users`                                     | Sì       | Sì      |
| `asServiceRole.*`                           | No       | Sì      |
| `asServiceRole.connectors` (OAuth dell'app) | No       | Sì      |
| `asServiceRole.sso`                         | No       | Sì      |

Le funzioni backend usano `Deno.serve()` e `createClientFromRequest(req)` per ottenere un client correttamente autenticato.

<Note>Questa pagina è stata tradotta utilizzando l'IA. Per informazioni più accurate e aggiornate, consulta la [versione inglese](/). </Note>
