К основному содержанию
скилл CX Codex

base44-sdk — скилл для Claude Code: что делает и установка

Скилл помогает писать код для Base44 через JavaScript SDK: работать с сущностями, функциями, realtime actors и AI gateway.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add base44/skills --skill base44-sdk -a claude-code
Открыть на GitHub

Что делает base44-sdk

Скилл даёт справку по Base44 JavaScript SDK и его модулям. С ним агент работает с удалёнными сущностями, backend-функциями, realtime actors и AI agents, а также вызывает AI gateway для генерации кода, изображений, видео, речи и AI-решений. Actors используют как realtime/WebSocket-примитив для совместных досок, присутствия, живых курсоров, чата и аукционов.

В материалах разобраны точные имена методов SDK: например, functions.invoke, auth.me(), entities.Task.create и actors.ChatRoom(roomId).connect(). Это помогает не переносить в Base44 API-паттерны из Firebase или Supabase. Для внешнего приложения показан клиент createClient({ appId: "your-app-id" }).

Проект Base44 должен быть уже инициализирован: без base44/config.jsonc этот скилл не подходит для создания нового проекта. Для новых проектов сначала нужен base44-cli. Это повод проверить конфигурацию до написания кода.

Какие задачи решает

  • работать с сущностями Base44 через SDK
  • вызывать backend-функции правильным методом
  • подключать realtime actors по идентификатору комнаты
  • получать текущего пользователя через auth.me()
  • обращаться к AI gateway из приложения

Примеры запросов агенту

  • «Проверь base44/config.jsonc и добавь функцию для чтения и обновления сущностей через Base44 SDK».
  • «Реализуй комнату с realtime actor и подпиши клиент на сообщения через actors.ChatRoom(roomId).connect()».
  • «Покажи правильный вызов backend-функции Base44 и проверь имена методов по скиллу».

Как установить base44-sdk

1Через Skills CLI (Vercel)

npx skills add base44/skills --skill base44-sdk -a claude-code

2Вручную: положить файлы

~/.claude/skills/base44-sdk/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/base44-sdk/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Из того же набора4

Похожие

ai-sdk vercel Скилл помогает писать код на базе Vercel AI SDK и не допускать устаревших API. Он проверяет локальную документацию пакета перед генерацией. CX Codex +1 66 100установок aws-sdk-java-v2-bedrock giuseppe-trisciuoglio Скилл подсказывает агенту, как вызывать модели Amazon Bedrock через AWS SDK for Java 2.x: текст, картинки, эмбеддинги и стриминг. CX Codex +1 3 700установок sentry-python-sdk getsentry Скилл сканирует Python-проект и ведёт через настройку Sentry: ошибки, трейсинг, профилирование, логи, кроны и AI-мониторинг. CX Codex +1 2 600установок openai-agents-sdk laguagu Скилл помогает писать агентов на Python-библиотеке openai-agents: настраивать передачу контекста между агентами, инструменты через @function_tool, стриминг и сессии в SQLite. CX Codex +1 2 200установок sap-cloud-sdk-ai-python secondsky Подключает пакет sap-ai-sdk-gen к проектам на Python. Помогает обращаться к языковым моделям через SAP AI Core и настраивать оркестрацию запросов. CX Codex +1 545установок copilot-sdk intellectronica Подсказывает агенту, как правильно работать с GitHub Copilot SDK: установка, авторизация, разрешения, события и сессии на пяти языках. CX Codex +1 531установок

Рядом в теме «Бэкенд и API»

Всё по теме «Бэкенд и API» →

Вопросы о base44-sdk

Как установить base44-sdk в Claude Code?

Выполните npx skills add base44/skills --skill base44-sdk -a claude-code, затем повторите npx skills add base44/skills --skill base44-sdk -a claude-code. После установки файл доступен по пути ~/.claude/skills/base44-sdk/SKILL.md.

Что делает base44-sdk?

Скилл объясняет, как использовать Base44 JavaScript SDK для сущностей, backend-функций, realtime actors, AI agents и AI gateway. Он также помогает сверять реальные имена методов перед написанием кода.

Можно ли использовать base44-sdk для нового проекта Base44?

Скилл рассчитан на уже инициализированный проект с base44/config.jsonc. Для создания нового проекта сначала используется base44-cli.

Исходный текст

SKILL.md · MIT
---
name: base44-sdk
description: "The base44 SDK is the library to communicate with base44 services. In projects, you use it to communicate with remote resources (entities, backend functions, realtime actors, ai agents, and the AI gateway for code agents, image, video, and speech generation, and AI decisions) and to write backend functions and actors. This skill is the place for learning about available modules and types, including actors — the realtime/WebSocket primitive for multiplayer, collaborative boards, presence and live cursors, in-room chat, and live auctions. When you plan or implement a feature, you must learn this skill"
---

# Base44 Coder

Build apps on the Base44 platform using the Base44 JavaScript SDK.

## ⚡ IMMEDIATE ACTION REQUIRED - Read This First

This skill activates on ANY mention of "base44" or when a `base44/` folder exists. **DO NOT read documentation files or search the web before acting.**

**Your first action MUST be:**
1. Check if `base44/config.jsonc` exists in the current directory
2. If **YES** (existing project scenario):
   - This skill (base44-sdk) handles the request
   - Implement features using Base44 SDK
   - Do NOT use base44-cli unless user explicitly requests CLI commands
3. If **NO** (new project scenario):
   - Transfer to base44-cli skill for project initialization
   - This skill cannot help until project is initialized

## When to Use This Skill vs base44-cli

**Use base44-sdk when:**
- Building features in an **EXISTING** Base44 project
- `base44/config.jsonc` already exists in the project
- Base44 SDK imports are present (`@base44/sdk`)
- Writing JavaScript/TypeScript code using Base44 SDK modules
- Implementing functionality, components, or features
- User mentions: "implement", "build a feature", "add functionality", "write code for"
- User says "create a [type] app" **and** a Base44 project already exists

**DO NOT USE base44-sdk for:**
- ❌ Initializing new Base44 projects (use `base44-cli` instead)
- ❌ Empty directories without Base44 configuration
- ❌ When user says "create a new Base44 project/app/site" and no project exists
- ❌ CLI commands like `npx base44 create`, `npx base44 deploy`, `npx base44 login` (use `base44-cli`)

**Skill Dependencies:**
- `base44-sdk` assumes a Base44 project is **already initialized**
- `base44-cli` is a **prerequisite** for `base44-sdk` in new projects
- If user wants to "create an app" and no Base44 project exists, use `base44-cli` first

**State Check Logic:**
Before selecting this skill, verify:
- IF (user mentions "create/build app" OR "make a project"):
  - IF (directory is empty OR no `base44/config.jsonc` exists):
    → Use **base44-cli** (project initialization needed)
  - ELSE:
    → Use **base44-sdk** (project exists, build features)

## Quick Start

```javascript
// 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
// 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("[email protected]", "password");
```

## ⚠️ CRITICAL: Do Not Hallucinate APIs

**Before writing ANY Base44 code, verify method names against this table or [QUICK_REFERENCE.md](references/QUICK_REFERENCE.md).**

Base44 SDK has unique method names. Do NOT assume patterns from Firebase, Supabase, or other SDKs.

### Authentication - WRONG vs CORRECT

| ❌ WRONG (hallucinated) | ✅ CORRECT |
|------------------------|-----------|
| `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()` (no listener, call when needed) |
| `currentUser` | `await auth.me()` |

### Functions - WRONG vs CORRECT

| ❌ WRONG (hallucinated) | ✅ CORRECT |
|------------------------|-----------|
| `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)` |

### Integrations - WRONG vs CORRECT

| ❌ WRONG (hallucinated) | ✅ CORRECT |
|------------------------|-----------|
| `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})` |

> **Exception:** an OpenAI-compatible client (e.g. the Vercel AI SDK or the `openai` SDK) **is** correct when pointed at `base44.asServiceRole.aiGateway.connection()` — that's how you build code agents (agent loops with tools) and call the gateway's image, video, and speech endpoints. Use `InvokeLLM` only for a single call with no tools. See [ai-gateway.md](references/ai-gateway.md).

### Actors - WRONG vs CORRECT

| ❌ WRONG (hallucinated) | ✅ CORRECT |
|------------------------|-----------|
| `actors.connect('ChatRoom', roomId)` | `actors.ChatRoom(roomId).connect()` |
| `actors.ChatRoom.connect(roomId)` | `actors.ChatRoom(roomId).connect()` |
| `actors.ChatRoom(roomId).subscribe(cb)` | subscribe on the **connection**: `const conn = actors.ChatRoom(roomId).connect(); conn.subscribe(cb)` |
| `room.on('message', cb)` | `room.subscribe(cb)` (one callback receives every message) |
| `room.emit(data)` | `room.send(data)` |
| `new WebSocket(...)` for app realtime | `base44.actors.<Name>(id).connect()` |
| `const unsub = room.subscribe(cb); unsub()` | `const sub = room.subscribe(cb); sub.unsubscribe()` |

> **The two `subscribe()` methods return different shapes.** `Connection.subscribe()` (actors) returns an object — `sub.unsubscribe()`. `entities.<Name>.subscribe()` returns the unsubscribe **function** itself — `unsub()`. Don't carry one convention to the other.

### Entities - WRONG vs CORRECT

| ❌ WRONG (hallucinated) | ✅ CORRECT |
|------------------------|-----------|
| `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)` |

## SDK Modules

| Module | Purpose | Reference |
|--------|---------|-----------|
| `entities` | CRUD operations on data models | [entities.md](references/entities.md) |
| `auth` | Login, register, user management | [auth.md](references/auth.md) |
| `agents` | AI conversations and messages | [base44-agents.md](references/base44-agents.md) |
| `functions` | Backend function invocation | [functions.md](references/functions.md) |
| `actors` | Realtime rooms over WebSockets (multiplayer, collaboration, presence) | [actors.md](references/actors.md) |
| `integrations` | AI, email, file uploads, custom APIs | [integrations.md](references/integrations.md) |
| `aiGateway` | Base44's AI gateway: code agents, images, videos, speech, and structured evaluations (Jev) | [ai-gateway.md](references/ai-gateway.md) |
| `analytics` | Track custom events and user activity | [analytics.md](references/analytics.md) |
| `appLogs` | Log user activity in app | [app-logs.md](references/app-logs.md) |
| `users` | Invite users to the app | [users.md](references/users.md) |
| `asServiceRole.connectors` | App-scoped OAuth tokens (service role only) | [connectors.md](references/connectors.md) |
| `asServiceRole.sso` | SSO token generation (service role only) | [sso.md](references/sso.md) |

For client setup and authentication modes, see [client.md](references/client.md).

### TypeScript and type registries

Each reference file includes a "Type Definitions" section with TypeScript interfaces and types for the module's methods, parameters, and return values.

**Getting typed entities, functions, actors, and agents:** The Base44 CLI generates types from your project resources (entities, functions, actors, agents), including augmentations to `EntityTypeRegistry`, `FunctionNameRegistry`, `ActorNameRegistry`, and `AgentNameRegistry`, and wires them into your project so you get autocomplete and type checking without manual setup. For how to generate types, use the **base44-cli** skill.

**Manual augmentation:** You can instead augment the registries yourself in a `.d.ts` file; see the Type Definitions sections in [entities.md](references/entities.md), [functions.md](references/functions.md), [actors.md](references/actors.md), and [base44-agents.md](references/base44-agents.md). Actor **message** types are always hand-authored — augment `ActorRegistry` so the actor and its clients share one definition.

## Installation

Install the Base44 SDK:

```bash
npm install @base44/sdk
```

**Important:** Never assume or hardcode the `@base44/sdk` package version. Always install without a version specifier to get the latest version.

## Creating a Client (External Apps)

When creating a client in external apps, **ALWAYS use `appId` as the parameter name**:

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

**Required parameter:** `appId` (string) - Your Base44 application ID

**Optional parameters:**
- `token` (string) - Pre-authenticated user token
- `options` (object) - Configuration options
  - `options.onError` (function) - Global error handler

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

## Module Selection

**Working with app data?**
- Create/read/update/delete records → `entities`
- Import data from file → `entities.importEntities()`
- Realtime updates → `entities.EntityName.subscribe()`

**User management?**
- Login/register/logout → `auth`
- Get current user → `auth.me()`
- Update user profile → `auth.updateMe()`
- Invite users → `users.inviteUser()`

**AI features?**
- Chat with AI agents → `agents` (requires logged-in user)
- Create new conversation → `agents.createConversation()`
- Manage conversations → `agents.getConversations()`
- Generate text/JSON with AI → `integrations.Core.InvokeLLM()`
- Generate one image with default settings → `integrations.Core.GenerateImage()`
- Several images, a specific model/aspect ratio/resolution, reference images, or edits → `aiGateway` images (see [ai-gateway.md](references/ai-gateway.md#generate-and-edit-images))
- Generate a simple text-to-video → `integrations.Core.GenerateVideo()`; model choice, references, or frames → `aiGateway` videos, an async job (see [ai-gateway.md](references/ai-gateway.md#generate-videos))
- Text-to-speech (TTS) or read-aloud → [speech guide](references/ai-gateway.md#generate-speech) for browser/Core/gateway selection; read it before implementing model-specific controls or editing existing gateway speech code
- Classify, score, or route a record against criteria → `aiGateway` with `provider: "typesafe"` (Jev), not `InvokeLLM` with a JSON schema (see [ai-gateway.md](references/ai-gateway.md#ai-decisions-jev))
- Build a custom agent with tools (backend, agent SDK on the AI gateway) → `aiGateway` (see [ai-gateway.md](references/ai-gateway.md))

**Custom backend logic?**
- Run server-side code → `functions.invoke()`
- Need admin access → `base44.asServiceRole.functions.invoke()`

**Realtime shared session?**
- Multiplayer, collaborative board/doc, presence, live cursors, in-room chat → `actors.<Name>(roomId).connect()` (see [actors.md](references/actors.md))
- Just keeping a list of records live on screen → `entities.EntityName.subscribe()`, **not** an actor

**External services?**
- Send emails → `integrations.Core.SendEmail()`
- Upload files → `integrations.Core.UploadFile()`
- Custom APIs → `integrations.custom.call()`
- App-scoped OAuth (app builder's account) → `asServiceRole.connectors.getConnection()` (backend only)

**Tracking and analytics?**
- Track custom events → `analytics.track()`
- Log page views/activity → `appLogs.logUserInApp()`

## Common Patterns

### Filter and Sort Data

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

### Protected Routes (check auth)

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

### Backend Function Call

```javascript
// 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
import { createClientFromRequest } from "npm:@base44/sdk";

export default async function (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 });
}
```

### Realtime Room (Actor)

```javascript
// Frontend — connect inside useEffect and always clean up
useEffect(() => {
  const room = base44.actors.ChatRoom(roomId).connect();
  const sub = room.subscribe((msg) => {
    if (msg.type === "message") setMessages((prev) => [...prev, msg]);   // switch on type; drop unknowns
  });
  return () => { sub.unsubscribe(); room.close(); };   // NOTE: actors return { unsubscribe() },
}, [roomId]);                                          // entities.subscribe() returns the function itself

// Actor — base44/actors/ChatRoom/entry.ts
import { Actor } from "base44:runtime/actors";

export default class ChatRoom extends Actor {
  handleConnect(conn) { conn.send({ type: "welcome" }); }        // one client
  handleMessage(conn, msg) {
    // Always validate: the payload is attacker-controlled and msg can even be null.
    if (msg?.type !== "message" || typeof msg.text !== "string") return;
    this.broadcast({ type: "message", text: msg.text.slice(0, 2000) });   // everyone
  }
  handleClose(conn) {}
}
```

### Service Role Access

Use `asServiceRole` in backend functions for admin-level operations. Actors expose `this.client.asServiceRole` for validated, room-owned work such as persisting canonical results; use verified `conn.identity.userId` from an authenticated connection for explicit user attribution. See [actors.md](references/actors.md).

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

| Capability | Frontend | Backend |
|------------|----------|---------|
| `entities` (user's data) | Yes | Yes |
| `auth` | Yes | Yes |
| `agents` | Yes | Yes |
| `functions.invoke()` | Yes | Yes |
| `functions.fetch()` | Yes | Yes |
| `actors` (connect to a room) | Yes | No — the actor *is* the server side |
| `integrations` | Yes | Yes |
| `aiGateway` | No | Yes |
| `analytics` | Yes | Yes |
| `appLogs` | Yes | Yes |
| `users` | Yes | Yes |
| `asServiceRole.*` | No | Yes |
| `asServiceRole.connectors` (app OAuth) | No | Yes |
| `asServiceRole.sso` | No | Yes |

Backend functions `export default` an async request handler and use `createClientFromRequest(req)` to get a properly authenticated client.

© base44 · MIT · base44/skills

Смотрите также

Спонсоры проекта

Компании, которые помогают держать аналитику открытой