Skip to main content

Initialize

NPM Version

@cloudbase/js-sdk allows you to use JavaScript to access CloudBase services and resources on the web, such as PC Web pages and WeChat public platform H5.

Note

The current @cloudbase/js-sdk version has launched v3 next. If you need to use v3 next, which supports browser, Node.js, React Native, and other general JavaScript runtime environments, please refer to the v3 next documentation.

Finish MCP setup first, then select a prompt to start your AI-native development journey

Prerequisites

Configure the Secure Domain Name

Before using @cloudbase/js-sdk, you need to configure the secure domain name, otherwise you will encounter a CORS error. For details, refer to: Secure Source

Configuration Steps:

  1. Go to CloudBase Platform / Environment Configuration / Security Configuration
  2. Add a website domain name (for example: www.example.com)
  3. Takes effect about 10 minutes after configuration

💡 Note:

  • Only domain names in the secure domain name list can use the CloudBase JS SDK to protect your data security
  • For local development, add localhost or 127.0.0.1 and the port to the secure domain name list
  • If you encounter a CORS error, please check whether the secure domain name configuration is correct

Install and Initialize

Install the 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 viewed at NPM.

Initialization Parameters

FieldTypeRequiredDefaultDescription
envstringYes-CloudBase environment ID
regionstringNoap-shanghaiRegion: ap-shanghai (default), ap-guangzhou, ap-singapore
langstringNozh-CNSpecified language: zh-CN (default), en-US
accessKeystringNo-Anonymous user authentication parameter, can be exposed in the browser, used to access public resources

⚠️ Note: The region of the currently used environment must match the specified region.

Login Authentication

js-sdk uses end-user permissions. You must log in before calling CloudBase capabilities.

For details, see: Anonymous Login

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

const { data, error } = await app.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",
});

Use English Prompt

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

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