Skip to main content

Initialization

NPM Version Node Version

@cloudbase/js-sdk is a cross-platform JavaScript SDK that lets you use JavaScript to access CloudBase services and resources across Web browsers, Node.js servers (Cloud Functions, CloudRun, self-hosted servers, etc.), WeChat Mini Programs, React Native, and more.

Beta

@cloudbase/js-sdk v4 is a Beta release. The npm latest tag is still v3, so npm install @cloudbase/js-sdk installs v3. For production, use JS SDK v3. To try v4, install @cloudbase/js-sdk@beta.

The Node.js adapter is built in, so you do not need to install @cloudbase/node-sdk separately. Authentication uses the GoTrue client by default. Call it with app.auth().

Quick Start​

Get started with CloudBase in just 3 steps:

npm install @cloudbase/js-sdk@beta -S
import cloudbase from "@cloudbase/js-sdk";

const app = cloudbase.init({
env: "your-env-id", // Replace with your environment ID
accessKey: "your-publishable-key", // Replace with your Publishable Key
});

// Start using CloudBase
const db = app.rdb();
const { data, error } = await db.from("todos").select();
Get Publishable Key

Go to CloudBase Platform / API Key Configuration to generate one. Publishable Key is the recommended auth method for Web — no extra login steps needed.


Deprecated modules left unmounted​

These three modules are deprecated. Installing @cloudbase/js-sdk does not install their packages. To keep the old calls working, install each package, import its register function, then call init. app.database(), app.mysql(), and app.rdb() still ship with the main package.

ModuleCallInstallImport
Document realtimecollection.watch()@cloudbase/realtimeregisterRealtime
Data modelsapp.models@cloudbase/modelregisterModel
HTTP APIapp.apis@cloudbase/apisregisterApis
npm install @cloudbase/realtime @cloudbase/model @cloudbase/apis -S
import cloudbase from "@cloudbase/js-sdk";
import { registerRealtime } from "@cloudbase/realtime";
import { registerModel } from "@cloudbase/model";
import { registerApis } from "@cloudbase/apis";

registerRealtime(cloudbase);
registerModel(cloudbase);
registerApis(cloudbase);

collection.watch() comes from @cloudbase/realtime. app.realtime() comes from registerRealtimeJs in the main package.


Installing the SDK​

# npm
npm install @cloudbase/js-sdk@beta -S

# yarn
yarn add @cloudbase/js-sdk@beta

Full import:

import cloudbase from "@cloudbase/js-sdk";

const app = cloudbase.init({
env: "your-env-id",
region: "ap-shanghai", // Defaults to Shanghai region if not specified
});

On-demand import (reduce bundle size):

// Core (required)
import cloudbase from "@cloudbase/js-sdk/app";
import { registerAuth } from "@cloudbase/js-sdk/auth";
import { registerMySQL } from "@cloudbase/js-sdk/mysql";
import { registerFunctions } from "@cloudbase/js-sdk/functions";
import { registerStorage } from "@cloudbase/js-sdk/storage";
// Deprecated. Install @cloudbase/model separately.
import { registerModel } from "@cloudbase/model";
import { registerRealtimeJs } from "@cloudbase/js-sdk/realtime-js";
import { registerAi } from "@cloudbase/js-sdk/ai";
import { registerCloudrun } from "@cloudbase/js-sdk/cloudrun";

registerAuth(cloudbase);
registerMySQL(cloudbase);

const app = cloudbase.init({
env: "your-env-id",
region: "ap-shanghai",
});

const auth = app.auth();
const db = app.rdb();
ModulePackageRegister functionFull import
Core@cloudbase/js-sdk/app-Yes
Auth@cloudbase/js-sdk/authregisterAuthYes
Cloud Functions@cloudbase/js-sdk/functionsregisterFunctionsYes
Cloud Storage@cloudbase/js-sdk/storageregisterStorageYes
Document database@cloudbase/js-sdk/databaseregisterDatabaseYes
MySQL / PostgreSQL@cloudbase/js-sdk/mysqlregisterMySQLYes
Realtime@cloudbase/js-sdk/realtime-jsregisterRealtimeJsYes
AI@cloudbase/js-sdk/airegisterAiYes
CloudBase Run@cloudbase/js-sdk/cloudrunregisterCloudrunYes
Document realtime@cloudbase/realtimeregisterRealtimeNo, deprecated
Data models@cloudbase/modelregisterModelNo, deprecated
HTTP API@cloudbase/apisregisterApisNo, deprecated
Note
  • @cloudbase/js-sdk/app is required
  • Document realtime, data models, and HTTP API are deprecated. A full install does not include them. See Deprecated modules left unmounted
  • Realtime (registerRealtimeJs) provides app.realtime(). See Realtime
  • On-demand imports keep the bundle smaller

For the latest version number, visit NPM.


Initialization Parameters​

Common Parameters​

FieldTypeRequiredDefaultDescription
envstringYes-CloudBase environment ID. Defaults to current env ID in Cloud Functions
regionstringNoap-shanghaiRegion: ap-shanghai (default), ap-guangzhou, ap-singapore
langstringNozh-CNLanguage: zh-CN (default), en-US
accessKeystringNo-CloudBase API Key / Publishable Key for authentication
timeoutnumberNo15000Request timeout (ms)
persistence'local' | 'session' | 'none'No'local'Where the session is stored. 'local' uses local storage, 'session' uses session storage, 'none' keeps it in memory
debugbooleanNofalsetrue enables debug logs, including GoTrue debug logs. Auth prints OAuth debug messages. On NETWORK_ERROR, stderr prints the status and requestId; a string body also prints its first 1024 characters
throwbooleanNoFollows authModeWhether business errors are thrown. supabase (default) is false and returns { code, message, requestId }. cloudbase is true and throws. An explicit value wins. With throw: true, auth methods throw
authMode'supabase' | 'cloudbase'NosupabaseAuth implementation. supabase uses GoTrue; cloudbase is the compatibility mode and uses CloudBase Auth
authobjectNo-Auth options. Fields are in the table below

auth fields are listed below. Except for detectSessionInUrl, they apply only to the default GoTrue client. With authMode: 'cloudbase', only detectSessionInUrl is passed to CloudBase Auth.

FieldTypeDefaultDescription
detectSessionInUrlboolean | functiontrueRestores a sign-in callback from the current URL. When set to a function, the URL is treated as a callback only if the function returns true. Set to false to turn this off
persistSessionbooleanSee descriptionWhether to write the session to storage. When omitted, this is true unless persistence is 'none'. An explicit value overrides persistence
autoRefreshTokenbooleanSee descriptionWhether to refresh the access token before it expires. When omitted, this matches the resolved persistSession
flowType'implicit' | 'pkce''implicit'OAuth callback style. 'implicit' reads tokens from the URL hash. 'pkce' exchanges the authorization code in the query string for a session

Other fields on auth are passed through to GoTrue. secretId, secretKey, sessionToken, secretType, and credentials are not. The SDK sets url, headers, fetch, storage, and storageKey; the same fields on auth have no effect. storageKey is always cloudbase-auth-js-${env}.

Note

The region of the current environment must match the region value specified during initialization.

Timeout Default Value

The default value of timeout varies by runtime environment:

  • Web / Mini Program and other non-Node.js environments: Defaults to 15000 (15 seconds).
  • Node.js environments (Cloud Functions, CloudBase Run, self-hosted servers, etc.): Defaults to no timeout (unlimited), to accommodate potentially long-running requests on the server side. If you need to limit the timeout, explicitly pass the timeout parameter.

Regardless of the environment, explicitly passing timeout takes precedence (maximum allowed value: 10 minutes).

Node.js-specific Parameters​

Node.js

The following parameters are only effective in Node.js environments.

FieldTypeRequiredDescription
secretIdstringNoTencent Cloud API key pair. Generate at Tencent Cloud Console / API Key Management. Can also be configured via TENCENTCLOUD_SECRETID env var
secretKeystringNoTencent Cloud API key pair. Can also be configured via TENCENTCLOUD_SECRETKEY env var
credentialsobjectNoCustom login private key containing private_key, private_key_id, env_id, used for createTicket to issue login credentials. Download from CloudBase Platform / Auth / Login Methods under "Custom Login"
contextobjectNoThe context parameter from the CloudRun entry function, used for signature-free calls

SYMBOL_CURRENT_ENV​

cloudbase.SYMBOL_CURRENT_ENV;

Use this field during initialization to specify using the current Cloud Function or CloudRun environment. Only effective in Cloud Function or CloudRun environments.

Note

In Cloud Functions or CloudRun, if init({}) is called without an env parameter, it defaults to the current environment ID instead of the CloudBase default environment. To use the default environment, specify init({env: tcb.SYMBOL_DEFAULT_ENV}).

import cloudbase from "@cloudbase/js-sdk";

// Initialize with the current Cloud Function's environment
const app = cloudbase.init({ env: cloudbase.SYMBOL_CURRENT_ENV });

exports.main = async (event, context) => {
// Business logic
};

Login Authentication​

After initialization, you need to complete authentication before using CloudBase features. Web and Node.js use different auth methods:

Web Login​

The Web SDK uses client-side user permissions, supporting the following login methods:

MethodUse CaseLogin Interaction Required
Publishable KeyPublic resource access❌ No login needed
Anonymous LoginUse without registration❌ No login needed
Account LoginUser identity required✅ Required

Publishable Key can be safely exposed in the browser for requesting publicly accessible resources — no extra login steps needed. For more details, refer to the documentation.

How to get: Go to CloudBase Platform / API Key Configuration to generate one.

const app = cloudbase.init({
env: "your-env-id",
accessKey: "your-publishable-key", // Fill in the generated Publishable Key
});

// No extra login.
const db = app.rdb();
const { data, error } = await db.from("todos").select();
Note

A Publishable Key can only be generated once. It is permanently valid and cannot be deleted. Keep it safe.

Node.js Authentication​

Node.js

The server supports multiple auth methods for accessing CloudBase resources (choose one).

Auth MethodDescriptionUse Case
Default (Cloud Function/CloudRun env)No parameters needed; auto-reads credentials from env varsCloud Functions, CloudRun
API KeyConfigure server API Key in CLOUDBASE_APIKEY env var; SDK reads it autoSelf-hosted servers
Publishable KeyPass accessKey in init; uses anonymous rolePublic resource access
secretId + secretKeyExplicitly pass Tencent Cloud API key pair in initSelf-hosted servers
contextCloudRun scenario; signature-free call via entry function context paramCloudRun

In Cloud Function environments, the SDK automatically reads auth info from environment variables. These are temporary access credentials — no manual configuration needed.

const cloudbase = require("@cloudbase/js-sdk");

const app = cloudbase.init({
env: "your-env-id",
});

exports.main = async (event, context) => {
// Use CloudBase features directly
};
Note

When the server does not use API Key or Publishable Key, it defaults to admin permissions. Otherwise, the API signatures, parameters, and return values are identical to the client side.