> ## 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 クライアントの作成と構成方法。

<Warning>
  このページは AI コーディングエージェントスキルの一部で、人間ではなくエージェント向けに書かれています。人間向けの Base44 ドキュメントは [デベロッパードキュメント](/developers) を参照してください。
</Warning>

# クライアントのセットアップ

Base44 クライアントの作成と構成方法。

## 目次

* [Base44 生成アプリ内](#in-base44-generated-apps)
* [外部アプリ内](#in-external-apps)
* [バックエンド関数内](#in-backend-functions)
* [認証モード](#authentication-modes) (匿名、ユーザー、サービスロール)
* [利用可能なモジュール](#available-modules)
* [クライアントメソッド](#client-methods)
* [クライアント構成オプション](#client-configuration-options)

## Base44 生成アプリ内

Base44 アプリ内では、クライアントは自動的に作成および構成されます。`@/api/base44Client` からインポートして `base44` として使用します:

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

## 外部アプリ内

Base44 を外部アプリのバックエンドとして使用する場合、SDK をインストールし、直接 `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);
    }
  }
});
```

**よくある間違い:**

* ❌ `createClient({ clientId: "..." })` - 誤ったパラメーター名
* ❌ `createClient({ id: "..." })` - 誤ったパラメーター名
* ❌ `createClient({ appId: "...", onError: ... })` - 誤: onError は options 内である必要
* ✅ `createClient({ appId: "..." })` - 正しいパラメーター名
* ✅ `createClient({ appId: "...", options: { onError: ... } })` - 正: options 内の onError

## バックエンド関数内

`createClientFromRequest()` は Base44 ホスト型のバックエンド関数用に設計されています。Base44 が注入するリクエストヘッダーから認証を抽出し、サービスロールアクセス (`base44.asServiceRole`) を含むクライアントを返します。フロントエンドと外部バックエンドには、代わりに `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 });
});
```

## 認証モード

| モード         | 取得方法                                                         | 権限         |
| ----------- | ------------------------------------------------------------ | ---------- |
| **匿名**      | トークンなしの `createClient({ appId })`                            | 公開データのみ    |
| **ユーザー**    | `loginViaEmailPassword()` 後、または `createClientFromRequest` 経由 | ユーザー自身のデータ |
| **サービスロール** | バックエンドの `base44.asServiceRole.*`                             | フル管理者アクセス  |

## 匿名モード

認証なし。公開リソースにのみアクセス可能。

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

## ユーザーモード

ユーザーがログインすると、クライアントは自動的にトークンを含めます。

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

## サービスロールモード

管理者レベルのアクセス。**バックエンドのみ。**

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

## 利用可能なモジュール

クライアントは以下のモジュールを公開します:

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

## クライアントメソッド

クライアントは以下のメソッドを提供します:

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

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

### setToken

後続のすべての API リクエストと WebSocket 接続の認証トークンを更新します。

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

### cleanup

WebSocket 接続を切断します。クライアントが不要になったとき、またはコンポーネントがアンマウントされたときに呼び出します。

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

## クライアント構成オプション

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

**⚠️ 重要:**

* パラメーター名は `clientId` や `id` ではなく `appId` です。誤ったパラメーター名を使用するとエラーが発生します。
* `onError` ハンドラーはトップレベルではなく `options` オブジェクト内にネストする必要があります。

## 型定義

### 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>このページは AI を使用して翻訳されました。最も正確で最新の情報については、[英語版](/) を参照してください。 </Note>
