Skip to main content

Initialization

NPM Version

@cloudbase/js-sdk allows you to access CloudBase services and resources using JavaScript on the Web (such as PC Web pages, WeChat Official Account H5, etc.).

Note

The current @cloudbase/js-sdk@latest version has been upgraded to v2. If you need to use v1, please refer to the v1 documentation.

Select a prompt to start your AI-native development journey

Prerequisites

Configure Security Domains

Before using @cloudbase/js-sdk, you need to configure security domains first, otherwise you will encounter CORS errors. For details, please refer to: Security Sources

Configuration Steps:

  1. Go to CloudBase Console/Environment Configuration/Security Settings
  2. Add your website domain (e.g., www.example.com)
  3. Configuration takes effect in approximately 10 minutes

💡 Note:

  • Only domains in the security domain list can use CloudBase JS SDK, this is to protect your data security
  • For local development, please add localhost or 127.0.0.1 to the security domain list
  • If you encounter CORS errors, please check if the security domain configuration is correct

Install and Initialize

Install SDK

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

# yarn
yarn add @cloudbase/js-sdk

Initialize SDK

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

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

The latest version number can be found on NPM.

Initialization Parameters

FieldTypeRequiredDefault ValueDescription
envstringYes-TCB environment ID
regionstringNoap-shanghaiRegion: ap-shanghai (default), ap-guangzhou, ap-singapore
langstringNozh-CNLanguage: zh-CN (default), en-US
accessKeystringNo-Anonymous user authentication parameter, can be exposed in browser for accessing public resources

⚠️ Note: The region of the environment you are using must match the specified region information!

Login Authentication

js-sdk uses client-side user permissions and requires login before calling CloudBase capabilities.

For details, please refer to: Anonymous Login

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

const auth = app.auth();
await auth.signInAnonymously();

Initialization Examples

Singapore Region

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

const app = cloudbase.init({
env: "your-env-id", // Replace with your environment ID
region: "ap-singapore",
});

Using English Prompts

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

const app = cloudbase.init({
env: "your-env-id", // Replace with your environment ID
lang: "en-US",
});