Skip to main content

Overview

Since v3.1, @cloudbase/js-sdk has a built-in Node.js adapter. You no longer need to install @cloudbase/node-sdk or @cloudbase/adapter-node separately to use the full CloudBase capabilities in Node.js environments (cloud functions, CloudBase Run, self-hosted servers, etc.).

Note

Node.js version >= 16.0 is required

Installation

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

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

Some server-side features depend on the following optional packages. Install them as needed:

PackagePurposeWhen to Install
@cloudbase/signature-nodejsRequest signing (TC3-HMAC-SHA256)When using secretId / secretKey auth
jsonwebtokenCustom login ticket signingWhen calling auth.createTicket
wsWebSocket connectionWhen using real-time data push
# Install as needed
npm install @cloudbase/signature-nodejs jsonwebtoken ws

Initialization

Basic Usage

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

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

Initialization Parameters

FieldTypeRequiredDescription
envstringNoTCB environment ID. If not specified in a cloud function environment, the current environment ID is used
accessKeystringNoCloudbase API Key, the highest priority authentication method. Can also be configured via the CLOUDBASE_APIKEY environment variable
authobjectNoAuthentication configuration, including secretId, secretKey, credentials, etc.
auth.secretIdstringNoTencent Cloud API key pair. Generate at Tencent Cloud Console / API Key Management. Can also be configured via the TENCENTCLOUD_SECRETID environment variable
auth.secretKeystringNoTencent Cloud API key pair. Can also be configured via the TENCENTCLOUD_SECRETKEY environment variable
auth.credentialsobjectNoCustom login private key, containing private_key, private_key_id, env_id, used for createTicket to issue login credentials. Download the private key from CloudBase Console / Authentication / Login Methods under "Custom Login"
contextobjectNoThe context parameter of the function-based CloudBase Run entry function, used for signature-free calls
timeoutnumberNoRequest timeout (ms), default 15000

Authentication

The server SDK can access CloudBase resources using different authentication methods. The following methods are supported (choose one):

Authentication MethodDescription
Default (Cloud Function / CloudBase Run)No parameters needed; credentials are automatically read from environment variables
API KeyConfigure the server API Key in the CLOUDBASE_APIKEY environment variable; the SDK reads it automatically
Publishable KeyPass accessKey in init to access with anonymous role identity
secretId + secretKeyExplicitly pass Tencent Cloud API key pair in init
contextIn CloudBase Run, use the entry function's context parameter for signature-free calls

Authentication Examples

In a cloud function environment, the SDK automatically reads authentication info from environment variables. These are temporary credentials and require no manual configuration.

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

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

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

Environment Info

parseContext

app.parseContext(context: object): object

Parses the context parameter of the cloud function entry function, converting runtime environment variables into a structured object.

  • Only effective in cloud function environments

参数

context
object

The context parameter of the cloud function entry function

返回

Return Value
Object

示例

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

exports.main = async (event, context) => {
const app = cloudbase.init({ env: "your-env-id" });

const envObj = app.parseContext(context);
console.log(envObj);
};

Identity Authentication

In addition to the following server-specific APIs, the server SDK can also call all client-side authentication APIs, such as email login, phone login, username/password login, linked login, etc. See Authentication for details.

getUserInfo

auth.getUserInfo(): IGetUserInfoResult

Gets the current request's user information (synchronous method, reads from cloud function runtime environment variables).

  • Synchronous method, no await needed
  • Only effective in cloud function / CloudBase Run environments

参数

无参数

返回

IGetUserInfoResult
Object

示例

const cloudbase = require("@cloudbase/js-sdk");
const app = cloudbase.init({ env: "your-env-id" });

exports.main = async (event, context) => {
const { openId, appId, uid, customUserId } = app.auth.getUserInfo();
console.log(openId, appId, uid, customUserId);
};

getEndUserInfo

async auth.getEndUserInfo(uid?: string): Promise<IGetEndUserInfoResult>

Gets detailed end-user information.

  • When uid is not provided, returns the current request user's information
  • When uid is provided, calls the admin API to query the specified user
  • No permission to call this API when using API Key or Publishable Key

参数

uid
string

CloudBase user identity. If not provided, reads the current user info from environment variables

返回

Promise
IGetEndUserInfoResult

示例

const cloudbase = require("@cloudbase/js-sdk");
const app = cloudbase.init({ env: "your-env-id" });

exports.main = async (event, context) => {
// Without uid, gets the current request's user info
const { userInfo } = await app.auth.getEndUserInfo();
console.log(userInfo);
};

queryUserInfo

async auth.queryUserInfo(query: IUserInfoQuery): Promise<any>

Queries user information by conditions.

  • Supports querying by uid, platform, and platformId
  • If uid is specified, it takes priority
  • No permission to call this API when using API Key or Publishable Key

参数

query
IUserInfoQuery

返回

Promise
Object

示例

const cloudbase = require("@cloudbase/js-sdk");
const app = cloudbase.init({ env: "your-env-id" });

exports.main = async (event, context) => {
const res = await app.auth.queryUserInfo({ uid: "user-uid" });
console.log(res.userInfo);
};

getClientIP

auth.getClientIP(): string

Gets the client IP address.

  • Synchronous method, reads from the TCB_SOURCE_IP environment variable
  • Only effective in cloud function / CloudBase Run environments

参数

无参数

返回

Return Value
string

Client IP address

示例

const cloudbase = require("@cloudbase/js-sdk");
const app = cloudbase.init({ env: "your-env-id" });

exports.main = async (event, context) => {
const ip = app.auth.getClientIP();
console.log("Client IP:", ip);
};

createTicket

async auth.createTicket(uid: string, options?: ICreateTicketOpts): Promise<string>

Creates a custom login credential Ticket, signed as a JWT using an RSA private key. The client can exchange this Ticket for a login session.

参数

uid
string

Developer-defined unique user ID (4-32 characters, supports letters, numbers, and some special characters)

options
ICreateTicketOpts

返回

Promise
string

Custom login credential Ticket, in the format "{private_key_id}/@@/{jwt_token}"

示例

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

const app = cloudbase.init({
env: "your-env-id",
auth: {
credentials: require("/path/to/tcb_custom_login.json"),
},
});

exports.main = async (event, context) => {
const ticket = await app.auth.createTicket("custom-user-id-123", {
refresh: 3600 * 1000, // 1 hour refresh
});
console.log(ticket);
// Return ticket to the client, which calls signInWithCustomTicket to complete login
};

CloudBase Capabilities

The server SDK shares the same API as the client SDK. The following CloudBase capabilities are called in the same way as on the client side. Please refer to the corresponding documentation:

CapabilityDocumentation Link
Cloud FunctionsCloud Functions
CloudBase RunCloudBase Run
Cloud StorageCloud Storage
Document DatabaseDocument Database
MySQL DatabaseMySQL Database
Data ModelsData Models
AIAI
APIsAPIs
Note

When not using API Key or Publishable Key, the server uses admin permissions by default. Other than that, the API signatures, parameters, and return values are the same as the client side.


Notifications

sendTemplateNotification

app.sendTemplateNotification(params: object, opts?: object): Promise<object>

Sends a template message notification.

参数

params
Object
opts
Object

返回

Promise
Object

示例

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

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

exports.main = async (event, context) => {
const result = await app.sendTemplateNotification({
notifyId: "your-notify-id",
data: { orderId: "ORD-001", amount: 200 },
url: "https://your-domain.com/order/detail",
});
console.log(result);
};

Complete Example

Here is an example that demonstrates the comprehensive use of various server-side capabilities in a cloud function:

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

const app = cloudbase.init({
env: "your-env-id",
auth: {
credentials: require("./tcb_custom_login.json"), // Optional: custom login private key
},
});

const db = app.database();

exports.main = async (event, context) => {
const { action } = event;

switch (action) {
// Identity Authentication (server-specific)
case "getUserInfo": {
return app.auth.getUserInfo();
}
case "getEndUserInfo": {
return app.auth.getEndUserInfo(event.uid);
}
case "createTicket": {
return app.auth.createTicket(event.customUserId, {
refresh: 3600 * 1000,
});
}

// Database Operations (same as client-side)
case "dbQuery": {
return db.collection("todos").where({ completed: false }).get();
}

// Cloud Function Invocation (same as client-side)
case "callFunction": {
return app.callFunction({
name: "another-function",
data: { key: "value" },
});
}

// Cloud Storage (same as client-side)
case "getTempFileURL": {
return app.getTempFileURL({
fileList: ["cloud://env-id.xxx/images/photo.png"],
});
}

// Environment Info (server-specific)
case "parseContext": {
return app.parseContext(context);
}

// Notifications (server-specific)
case "notify": {
return app.sendTemplateNotification({
notifyId: "xxx",
data: event.notifyData,
url: event.notifyUrl,
});
}

default:
return { error: `Unknown action: ${action}` };
}
};