Skip to main content

Initialize

NPM Version

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

Note

The current <1>@cloudbase/js-sdk@latest</1> version has been upgraded to v2. If you need to use v1, see the v1 document.

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 Cloud Development 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 Cloud Development 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 this value with your environment ID
region: "ap-shanghai", // Defaults to Shanghai region if not specified
});

The latest version number can be viewed at NPM.

Initialize parameter

FieldData TypeRequiredDefault ValueDescription
envstringYes-TCB 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 browser, for request to public accessed resource

⚠️ Note: The region of the currently used environment must be consistent with the specified region information.

Login Authentication

js-sdk uses C-end user permission. Log in to call cloud development capability.

For details, see Anonymous Login.

const app = cloudbase.init({
env: "your-env-id", // Replace this value 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 this value 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 this value with your environment ID
lang: "en-US",
});