base44-sdk

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Base44 Coder

Base44 开发工具

Build apps on the Base44 platform using the Base44 JavaScript SDK.
使用Base44 JavaScript SDK在Base44平台上构建应用。

⚡ 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
当提及“base44”或当前目录存在
base44/
文件夹时,本技能将被激活。在操作前请勿阅读文档文件或搜索网络。
你的首要操作必须是:
  1. 检查当前目录下是否存在
    base44/config.jsonc
    文件
  2. 如果存在(现有项目场景):
    • 由本技能(base44-sdk)处理请求
    • 使用Base44 SDK实现功能
    • 除非用户明确要求CLI命令,否则请勿使用base44-cli
  3. 如果不存在(新项目场景):
    • 转至base44-cli技能进行项目初始化
    • 在项目初始化完成前,本技能无法提供帮助

When to Use This Skill vs base44-cli

何时使用本技能 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)
使用base44-sdk的场景:
  • 现有Base44项目中构建功能
  • 项目中已存在
    base44/config.jsonc
    文件
  • 项目中已导入Base44 SDK(
    @base44/sdk
  • 使用Base44 SDK模块编写JavaScript/TypeScript代码
  • 实现功能、组件或特性
  • 用户提及:“实现”、“构建功能”、“添加功能”、“编写代码实现”
  • 用户说“创建一个[类型]应用”Base44项目已存在
请勿使用base44-sdk的场景:
  • ❌ 初始化新的Base44项目(请使用
    base44-cli
  • ❌ 无Base44配置文件的空目录
  • ❌ 用户说“创建新的Base44项目/应用/站点”且当前无项目存在
  • ❌ CLI命令如
    npx base44 create
    npx base44 deploy
    npx base44 login
    (请使用
    base44-cli
技能依赖:
  • base44-sdk
    假设Base44项目已完成初始化
  • 在新项目中,
    base44-cli
    base44-sdk
    前置依赖
  • 如果用户想要“创建应用”且当前无Base44项目,请先使用
    base44-cli
状态检查逻辑: 在选择本技能前,请验证:
  • 如果(用户提及“创建/构建应用”或“创建项目”):
    • 如果(目录为空或不存在
      base44/config.jsonc
      ): → 使用base44-cli(需要项目初始化)
    • 否则: → 使用base44-sdk(项目已存在,构建功能)

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("user@example.com", "password");
javascript
// 在Base44生成的应用中,base44客户端已预先配置好并可用

// CRUD操作
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" });

// 获取当前用户
const user = await base44.auth.me();
javascript
// 外部应用
import { createClient } from "@base44/sdk";

// 重要提示:使用'appId'(而非'clientId'或'id')
const base44 = createClient({ appId: "your-app-id" });
await base44.auth.loginViaEmailPassword("user@example.com", "password");

⚠️ CRITICAL: Do Not Hallucinate APIs

⚠️ 关键提示:请勿虚构API

Before writing ANY Base44 code, verify method names against this table or QUICK_REFERENCE.md.
Base44 SDK has unique method names. Do NOT assume patterns from Firebase, Supabase, or other SDKs.
在编写任何Base44代码前,请对照下表或QUICK_REFERENCE.md验证方法名称。
Base44 SDK具有独特的方法名称。请勿假设其与Firebase、Supabase或其他SDK的模式相同。

Authentication - WRONG vs CORRECT

身份验证 - 错误示例 vs 正确示例

❌ 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()
❌ 错误(虚构)✅ 正确
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()
(无监听器,按需调用)
currentUser
await auth.me()

Functions - WRONG vs CORRECT

函数 - 错误示例 vs 正确示例

❌ 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)
❌ 错误(虚构)✅ 正确
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

集成 - 错误示例 vs 正确示例

❌ 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})
❌ 错误(虚构)✅ 正确
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})

Entities - WRONG vs CORRECT

实体 - 错误示例 vs 正确示例

❌ 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)
❌ 错误(虚构)✅ 正确
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

SDK模块

ModulePurposeReference
entities
CRUD operations on data modelsentities.md
auth
Login, register, user managementauth.md
agents
AI conversations and messagesbase44-agents.md
functions
Backend function invocationfunctions.md
integrations
AI, email, file uploads, custom APIsintegrations.md
connectors
OAuth tokens (service role only)connectors.md
analytics
Track custom events and user activityanalytics.md
appLogs
Log user activity in appapp-logs.md
users
Invite users to the appusers.md
For client setup and authentication modes, see client.md.
TypeScript Support: Each reference file includes a "Type Definitions" section with TypeScript interfaces and types for the module's methods, parameters, and return values.
模块用途参考文档
entities
数据模型的CRUD操作entities.md
auth
登录、注册、用户管理auth.md
agents
AI对话与消息base44-agents.md
functions
后端函数调用functions.md
integrations
AI、邮件、文件上传、自定义APIintegrations.md
connectors
OAuth令牌(仅服务角色可用)connectors.md
analytics
跟踪自定义事件与用户活动analytics.md
appLogs
在应用中记录用户活动app-logs.md
users
邀请用户加入应用users.md
关于客户端设置和身份验证模式,请查看client.md
TypeScript支持: 每个参考文档都包含“类型定义”部分,提供模块方法、参数和返回值的TypeScript接口与类型。

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.
安装Base44 SDK:
bash
npm install @base44/sdk
重要提示: 请勿假设或硬编码
@base44/sdk
的包版本。始终安装不带版本指定的包以获取最新版本。

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);
    }
  }
});
在外部应用中创建客户端时,请始终使用
appId
作为参数名
javascript
import { createClient } from "@base44/sdk";

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

// ❌ 错误 - 请勿使用以下方式:
// const base44 = createClient({ clientId: "your-app-id" });  // 错误
// const base44 = createClient({ id: "your-app-id" });        // 错误
必填参数:
appId
(字符串)- 你的Base44应用ID
可选参数:
  • token
    (字符串)- 预认证的用户令牌
  • options
    (对象)- 配置选项
    • options.onError
      (函数)- 全局错误处理函数
带错误处理的示例:
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 images →
    integrations.Core.GenerateImage()
Custom backend logic?
  • Run server-side code →
    functions.invoke()
  • Need admin access →
    base44.asServiceRole.functions.invoke()
External services?
  • Send emails →
    integrations.Core.SendEmail()
  • Upload files →
    integrations.Core.UploadFile()
  • Custom APIs →
    integrations.custom.call()
  • OAuth tokens (Google, Slack) →
    connectors
    (backend only)
Tracking and analytics?
  • Track custom events →
    analytics.track()
  • Log page views/activity →
    appLogs.logUserInApp()
处理应用数据?
  • 创建/读取/更新/删除记录 →
    entities
  • 从文件导入数据 →
    entities.importEntities()
  • 实时更新 →
    entities.EntityName.subscribe()
用户管理?
  • 登录/注册/登出 →
    auth
  • 获取当前用户 →
    auth.me()
  • 更新用户资料 →
    auth.updateMe()
  • 邀请用户 →
    users.inviteUser()
AI功能?
  • 与AI Agent对话 →
    agents
    (需要用户已登录)
  • 创建新对话 →
    agents.createConversation()
  • 管理对话 →
    agents.getConversations()
  • 使用AI生成文本/JSON →
    integrations.Core.InvokeLLM()
  • 生成图片 →
    integrations.Core.GenerateImage()
自定义后端逻辑?
  • 运行服务器端代码 →
    functions.invoke()
  • 需要管理员权限 →
    base44.asServiceRole.functions.invoke()
外部服务?
  • 发送邮件 →
    integrations.Core.SendEmail()
  • 上传文件 →
    integrations.Core.UploadFile()
  • 自定义API →
    integrations.custom.call()
  • OAuth令牌(Google、Slack) →
    connectors
    (仅后端可用)
跟踪与分析?
  • 跟踪自定义事件 →
    analytics.track()
  • 记录页面浏览/活动 →
    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
);
javascript
const pendingTasks = await base44.entities.Task.filter(
  { status: "pending", assignedTo: userId },  // 查询条件
  "-created_date",                             // 排序(降序)
  10,                                          // 数量限制
  0                                            // 跳过条数
);

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;
}
javascript
const user = await base44.auth.me();
if (!user) {
  // 跳转到自定义登录页面
  navigate('/login', { state: { returnTo: window.location.pathname } });
  return;
}

Backend Function Call

后端函数调用

javascript
// Frontend
const result = await base44.functions.invoke("processOrder", {
  orderId: "123",
  action: "ship"
});

// 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 });
});
javascript
// 前端
const result = await base44.functions.invoke("processOrder", {
  orderId: "123",
  action: "ship"
});

// 后端函数(Deno)
import { createClientFromRequest } from "npm:@base44/sdk";

Deno.serve(async (req) => {
  const base44 = createClientFromRequest(req);
  const { orderId, action } = await req.json();
  // 使用服务角色获取管理员权限进行处理
  const order = await base44.asServiceRole.entities.Orders.get(orderId);
  return Response.json({ success: true });
});

Service Role Access

服务角色访问

Use
asServiceRole
in backend functions for admin-level operations:
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");
在后端函数中使用
asServiceRole
执行管理员级别的操作:
javascript
// 用户模式 - 遵循权限限制
const myTasks = await base44.entities.Task.list();

// 服务角色 - 完全访问权限(仅后端可用)
const allTasks = await base44.asServiceRole.entities.Task.list();
const token = await base44.asServiceRole.connectors.getAccessToken("slack");

Frontend vs Backend

前端 vs 后端

CapabilityFrontendBackend
entities
(user's data)
YesYes
auth
YesYes
agents
YesYes
functions.invoke()
YesYes
integrations
YesYes
analytics
YesYes
appLogs
YesYes
users
YesYes
asServiceRole.*
NoYes
connectors
NoYes
Backend functions use
Deno.serve()
and
createClientFromRequest(req)
to get a properly authenticated client.
功能前端后端
entities
(用户数据)
auth
agents
functions.invoke()
integrations
analytics
appLogs
users
asServiceRole.*
connectors
后端函数使用
Deno.serve()
createClientFromRequest(req)
获取经过正确身份验证的客户端。