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.).
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:
| Package | Purpose | When to Install |
|---|---|---|
@cloudbase/signature-nodejs | Request signing (TC3-HMAC-SHA256) | When using secretId / secretKey auth |
jsonwebtoken | Custom login ticket signing | When calling auth.createTicket |
ws | WebSocket connection | When 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
| Field | Type | Required | Description |
|---|---|---|---|
env | string | No | TCB environment ID. If not specified in a cloud function environment, the current environment ID is used |
accessKey | string | No | Cloudbase API Key, the highest priority authentication method. Can also be configured via the CLOUDBASE_APIKEY environment variable |
auth | object | No | Authentication configuration, including secretId, secretKey, credentials, etc. |
auth.secretId | string | No | Tencent Cloud API key pair. Generate at Tencent Cloud Console / API Key Management. Can also be configured via the TENCENTCLOUD_SECRETID environment variable |
auth.secretKey | string | No | Tencent Cloud API key pair. Can also be configured via the TENCENTCLOUD_SECRETKEY environment variable |
auth.credentials | object | No | Custom 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" |
context | object | No | The context parameter of the function-based CloudBase Run entry function, used for signature-free calls |
timeout | number | No | Request timeout (ms), default 15000 |
Authentication
The server SDK can access CloudBase resources using different authentication methods. The following methods are supported (choose one):
| Authentication Method | Description |
|---|---|
| Default (Cloud Function / CloudBase Run) | No parameters needed; credentials are automatically read from environment variables |
| API Key | Configure the server API Key in the CLOUDBASE_APIKEY environment variable; the SDK reads it automatically |
| Publishable Key | Pass accessKey in init to access with anonymous role identity |
secretId + secretKey | Explicitly pass Tencent Cloud API key pair in init |
context | In CloudBase Run, use the entry function's context parameter for signature-free calls |
Authentication Examples
- Cloud Function (Default Auth)
- CloudBase Run
- Publishable Key
- secretId + secretKey
- API Key
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
};
In a function-based CloudBase Run environment, pass the context parameter for signature-free calls.
💡 Note: If
contextis provided butenvis not, theenvIDfromcontextwill be used as the environment ID.
const cloudbase = require("@cloudbase/js-sdk");
exports.main = async (event, context) => {
const app = cloudbase.init({
context,
});
// Use CloudBase capabilities
};
For detailed information about Publishable Key, please refer to the documentation.
- User Permissions: Anonymous user permissions
- Validity: Long-term valid
- How to Obtain: Get it from CloudBase Console / ApiKey Management
import tcb from "@cloudbase/node-sdk";
const app = tcb.init({
env: "your-env-id",
accessKey: "your-publishable-key",
});
Generate a key pair at Tencent Cloud Console / API Key Management.
const cloudbase = require("@cloudbase/js-sdk");
const app = cloudbase.init({
env: "your-env-id",
auth: {
secretId: "your-secretId",
secretKey: "your-secretKey",
},
});
Configure via the CLOUDBASE_APIKEY environment variable. In cloud functions, enable API key settings and add CLOUDBASE_APIKEY; the SDK reads it automatically.

const cloudbase = require("@cloudbase/js-sdk");
// No need to pass explicitly; the SDK reads from environment variables automatically
const app = cloudbase.init({
env: "your-env-id",
});
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
参数
The context parameter of the cloud function entry function
返回
示例
- Basic Example
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
awaitneeded - Only effective in cloud function / CloudBase Run environments
参数
无参数
返回
示例
- Basic Example
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
uidis not provided, returns the current request user's information - When
uidis provided, calls the admin API to query the specified user - No permission to call this API when using
API KeyorPublishable Key
参数
CloudBase user identity. If not provided, reads the current user info from environment variables
返回
示例
- Get Current User
- Query Specified User
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);
};
const cloudbase = require("@cloudbase/js-sdk");
const app = cloudbase.init({ env: "your-env-id" });
exports.main = async (event, context) => {
const { userInfo, requestId } = await app.auth.getEndUserInfo(
"target-user-uid"
);
console.log(userInfo);
};
queryUserInfo
async auth.queryUserInfo(query: IUserInfoQuery): Promise<any>
Queries user information by conditions.
- Supports querying by
uid,platform, andplatformId - If
uidis specified, it takes priority - No permission to call this API when using
API KeyorPublishable Key
参数
返回
示例
- Query by uid
- Query by Phone Number
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);
};
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({
platform: "PHONE",
platformId: "13800138000",
});
console.log(res.userInfo);
};
getClientIP
auth.getClientIP(): string
Gets the client IP address.
- Synchronous method, reads from the
TCB_SOURCE_IPenvironment variable - Only effective in cloud function / CloudBase Run environments
参数
无参数
返回
Client IP address
示例
- Basic Example
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.
- Requires
auth.credentials(custom login private key) to be passed ininit - Download the private key file from CloudBase Console / Authentication / Login Methods under "Custom Login"
- Requires dependency:
npm install jsonwebtoken
参数
Developer-defined unique user ID (4-32 characters, supports letters, numbers, and some special characters)
返回
Custom login credential Ticket, in the format "{private_key_id}/@@/{jwt_token}"
示例
- Basic Example
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:
| Capability | Documentation Link |
|---|---|
| Cloud Functions | Cloud Functions |
| CloudBase Run | CloudBase Run |
| Cloud Storage | Cloud Storage |
| Document Database | Document Database |
| MySQL Database | MySQL Database |
| Data Models | Data Models |
| AI | AI |
| APIs | APIs |
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.
- Notification policies must be pre-configured in CloudBase Console / Notification Management
- Trigger method should be set to "Manual Trigger"
参数
返回
示例
- Basic Example
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}` };
}
};