Complete guide for CloudBase Auth using the CloudBase Node SDK – caller identity, user lookup, custom login tickets, and server-side best practices.
If this environment only installed the current skill, start from the CloudBase main entry and use the published cloudbase/references/... paths for sibling skills.
https://cnb.cool/tencent/cloud/cloudbase/cloudbase-skills/-/git/raw/main/skills/cloudbase/SKILL.mdhttps://cnb.cool/tencent/cloud/cloudbase/cloudbase-skills/-/git/raw/main/skills/cloudbase/references/auth-nodejs/SKILL.mdKeep local references/... paths for files that ship with the current skill directory. When this file points to a sibling skill such as auth-tool or web-development, use the standalone fallback URL shown next to that reference.
@cloudbase/node-sdk, server-side auth, custom login tickets, or "who is calling".../auth-tool/SKILL.md (standalone fallback: https://cnb.cool/tencent/cloud/cloudbase/cloudbase-skills/-/git/raw/main/skills/cloudbase/references/auth-tool/SKILL.md)../auth-web/SKILL.md (standalone fallback: https://cnb.cool/tencent/cloud/cloudbase/cloudbase-skills/-/git/raw/main/skills/cloudbase/references/auth-web/SKILL.md)../http-api/SKILL.md (standalone fallback: https://cnb.cool/tencent/cloud/cloudbase/cloudbase-skills/-/git/raw/main/skills/cloudbase/references/http-api/SKILL.md)Use this skill whenever the task involves server-side authentication or identity in a CloudBase project, and the code is running in Node.js, for example:
Do NOT use this skill for:
@cloudbase/js-sdk (handle those with the auth-web skill, not this Node skill).When the user request mixes frontend and backend concerns (e.g. "build a web login page and a Node API that knows the user"), treat them separately:
When you load this skill to work on a task:
Clarify the runtime and responsibility
Ask the user:
Confirm CloudBase environment and SDK
env – CloudBase environment ID@cloudbase/node-sdk from npm if it is not already available.import tcb from "@cloudbase/node-sdk";
const app = tcb.init({ env: "your-env-id" });
const auth = app.auth();
Pick the relevant scenario from this file
getUserInfo scenarios.getEndUserInfo and queryUserInfo scenarios.createTicket.getClientIP scenario.Follow Node SDK API shapes exactly
auth.* methods and parameter shapes in this file as canonical.If you are unsure about an API
CloudBase Auth v2 separates where users log in from where backend code runs:
In practice, Node code usually does one or more of:
Identify the current caller
auth.getUserInfo() to read uid, openId, and customUserId.Look up other users
auth.getEndUserInfo(uid) when you know the CloudBase uid.auth.queryUserInfo({ platform, platformId, uid? }) when you only have login identifiers such as phone, email, username, or a custom ID.Issue custom login tickets
auth.createTicket(customUserId, options) and return the ticket to a trusted client.Log client IP for security
auth.getClientIP() returns the caller IP, which you can use for audit logs, anomaly detection, or access control.The scenarios later in this file turn these responsibilities into explicit, copy‑pasteable patterns.
This skill covers the following auth methods on the CloudBase Node SDK. Treat these method signatures as the only supported entry points for Node auth flows when using this skill:
getUserInfo(): IGetUserInfoResult
Returns { openId, appId, uid, customUserId } for the current caller.
getEndUserInfo(uid?: string, opts?: ICustomReqOpts): Promise<{ userInfo: EndUserInfo; requestId?: string }>
Returns detailed CloudBase end‑user profile for a given uid or for the current caller (when uid is omitted).
queryUserInfo(query: IUserInfoQuery, opts?: ICustomReqOpts): Promise<{ userInfo: EndUserInfo; requestId?: string }>
Finds a user by login identifier (platform + platformId) or uid.
getClientIP(): string
Returns the caller’s IP address when running in a supported environment (e.g. 云函数).
createTicket(customUserId: string, options?: ICreateTicketOpts): string
Creates a custom login ticket for the given customUserId that clients can exchange for a CloudBase login.
The exact field names and allowed values for EndUserInfo, IUserInfoQuery, and ICreateTicketOpts are defined by the official CloudBase Node SDK typings and documentation. When writing Node code, do not guess shapes; follow the SDK types and the examples in this file.
Use this when writing a CloudBase 云函数 that needs to interact with Auth:
import tcb from "@cloudbase/node-sdk";
const app = tcb.init({ env: "your-env-id" });
const auth = app.auth();
exports.main = async (event, context) => {
// Your logic here
};
Key points:
env as configured for the function’s CloudBase 环境.Use this when you need to know who is calling your cloud function:
import tcb from "@cloudbase/node-sdk";
const app = tcb.init({ env: "your-env-id" });
const auth = app.auth();
exports.main = async (event, context) => {
const { openId, appId, uid, customUserId } = auth.getUserInfo();
console.log("Caller identity", { openId, appId, uid, customUserId });
// Use uid / customUserId for authorization decisions
// e.g. check roles, permissions, or data ownership
};
Best practices:
uid as the canonical CloudBase user identifier.customUserId only when you have enabled 自定义登录 and mapped your own users.openId/appId alone for authorization; they are WeChat‑specific identifiers.Use this when you know a user’s CloudBase uid (for example, from a database record) and you need detailed profile information:
import tcb from "@cloudbase/node-sdk";
const app = tcb.init({ env: "your-env-id" });
const auth = app.auth();
exports.main = async (event, context) => {
const uid = "user-uid";
try {
const { userInfo } = await auth.getEndUserInfo(uid);
console.log("User profile", userInfo);
} catch (error) {
console.error("Failed to get end user info", error.message);
}
};
Best practices:
getEndUserInfo from trusted backend code only; do not expose it directly to untrusted clients.Use this when you want the current caller’s full profile without manually passing uid:
import tcb from "@cloudbase/node-sdk";
const app = tcb.init({ env: "your-env-id" });
const auth = app.auth();
exports.main = async (event, context) => {
try {
const { userInfo } = await auth.getEndUserInfo();
console.log("Current caller profile", userInfo);
} catch (error) {
console.error("Failed to get current caller profile", error.message);
}
};
This relies on the environment providing the caller’s identity (e.g. within a CloudBase 云函数). If called where no caller context exists, refer to the official docs and handle errors gracefully.
Use this when you only know a user’s login identifier (phone, email, username, or custom ID) and need their CloudBase profile:
import tcb from "@cloudbase/node-sdk";
const app = tcb.init({ env: "your-env-id" });
const auth = app.auth();
exports.main = async (event, context) => {
try {
// Find by phone number
const { userInfo: byPhone } = await auth.queryUserInfo({
platform: "PHONE",
platformId: "+86 13800000000",
});
// Find by email
const { userInfo: byEmail } = await auth.queryUserInfo({
platform: "EMAIL",
platformId: "test@example.com",
});
// Find by customUserId
const { userInfo: byCustomId } = await auth.queryUserInfo({
platform: "CUSTOM",
platformId: "your-customUserId",
});
console.log({ byPhone, byEmail, byCustomId });
} catch (error) {
console.error("Failed to query user info", error.message);
}
};
Best practices:
uid when you already have it; use queryUserInfo only when needed.platformId uses the exact format you used at sign‑up (e.g. +86 + phone number).Use this for logging or basic IP‑based checks:
import tcb from "@cloudbase/node-sdk";
const app = tcb.init({ env: "your-env-id" });
const auth = app.auth();
exports.main = async (event, context) => {
const ip = auth.getClientIP();
console.log("Caller IP", ip);
// e.g. block or flag suspicious IPs
};
Custom login lets you keep your existing user system while still mapping each user to a CloudBase account.
Before issuing tickets, install the custom login private key file from the CloudBase console and load it in Node:
import tcb from "@cloudbase/node-sdk";
import path from "node:path";
const app = tcb.init({
env: "your-env-id",
credentials: require(path.join(__dirname, "tcb_custom_login.json")),
});
const auth = app.auth();
Keep tcb_custom_login.json secret and never bundle it into frontend code.
Use this in backend code that has already authenticated your own user and wants to let them log into CloudBase:
import tcb from "@cloudbase/node-sdk";
const app = tcb.init({
env: "your-env-id",
credentials: require("/secure/path/to/tcb_custom_login.json"),
});
const auth = app.auth();
exports.main = async (event, context) => {
const customUserId = "your-customUserId";
const ticket = auth.createTicket(customUserId, {
refresh: 3600 * 1000, // access_token refresh interval (ms)
expire: 24 * 3600 * 1000, // ticket expiration time (ms)
});
// Return the ticket to the trusted client (e.g. via HTTP response)
return { ticket };
};
Constraints for customUserId (from official docs):
_-#@(){}[]:.,<>+#~.Best practices:
customUserId in your own user database and keep it stable over time.customUserId for multiple distinct people.This skill only covers Node-side ticket issuance. For the client-side flow:
@cloudbase/js-sdk's custom login support:ticket.auth.setCustomSignFunc(async () => ticketFromBackend).auth.signInWithCustomTicket() to finish login.Keep the responsibility clear:
Single source of truth for identity
uid as the primary key when relating end‑user records.customUserId only as a bridge to your own user system.Least privilege
uid, roles, and ownership, not just login success.getEndUserInfo / queryUserInfo results directly to clients.Error handling
auth.* calls in try/catch when they return promises.error.message (and error.code if present), but avoid logging sensitive data.Security
tcb_custom_login.json as you would any private key.Use this Node Auth skill whenever you need to:
uid or login identifier.For end‑to‑end experiences, pair this skill with:
@cloudbase/js-sdk).Treat the official CloudBase Auth Node SDK documentation as the canonical reference for Node auth APIs, and treat the scenarios in this file as vetted best‑practice building blocks.