WeChat Mini Program Cloud Server SDK
The `wx-server-sdk` is the official Software Development Kit for interacting with WeChat Mini Program Cloud Development services from within Cloud Functions. It provides a comprehensive set of APIs for accessing cloud resources such as Cloud Database (MongoDB-like), Cloud Storage (object storage), and invoking other Cloud Functions. The SDK is designed to run in a Node.js environment, specifically within the WeChat Cloud Function runtime. The current stable version is 3.0.4, last published approximately two months ago (as of early 2026). While there isn't a strict, publicly defined release cadence, updates are regularly issued to introduce new features, improve performance, and address bugs. Its primary differentiation lies in its deep integration with the WeChat ecosystem, offering seamless backend support for Mini Programs without needing to manage traditional servers.
Common errors
-
Error: Cannot find module 'wx-server-sdk'
cause The `wx-server-sdk` package has not been installed in the specific Cloud Function's `node_modules` directory.fixNavigate into the `cloudfunctions/<your-function-name>` directory and run `npm install --save wx-server-sdk`. -
TypeError: Cannot read properties of undefined (reading 'database')
cause The `cloud.init()` method was not called or failed, meaning the `cloud` object was not properly initialized before attempting to access its properties like `database`.fixAdd `cloud.init({ env: 'your-environment-id' });` at the beginning of your Cloud Function's `main` function. -
Error: 'collection' must be a string
cause The `collection()` method of the database was called without providing a valid string for the collection name.fixEnsure `db.collection('your_collection_name')` passes a non-empty string as the collection identifier. -
SyntaxError: 'await' is only valid in async functions and the top level bodies of modules
cause Using `await` inside a Cloud Function without declaring the function `async`.fixDeclare your Cloud Function's entry point `export async function main(event: any, context: any) { ... }`.
Warnings
- breaking Version 3.0.1 introduced a breaking change regarding BigInt serialization. Native `JSON.stringify` will serialize the SDK's built-in `BigInt` (implemented via `bigint.js`) as a string, not a number, potentially impacting existing code expecting numeric `BigInt` values in JSON output.
- gotcha Cloud Functions run in a Node.js environment and are granted unrestricted read/write access to Cloud Database and Cloud Storage by default. This powerful access model requires careful security consideration to prevent data breaches or unintended modifications.
- gotcha The `wx-server-sdk` must be installed within the specific Cloud Function's directory, not just at the project root level. Failing to do so will result in 'Cannot find module' errors at runtime.
- gotcha The `cloud.init()` method must be called exactly once at the entry point of your Cloud Function before any other cloud operations are performed. Forgetting this will lead to errors when attempting to use database, storage, or other cloud APIs.
Install
-
npm install wx-server-sdk -
yarn add wx-server-sdk -
pnpm add wx-server-sdk
Imports
- cloud
import { cloud } from 'wx-server-sdk';import cloud from 'wx-server-sdk';
- init
const { init } = require('wx-server-sdk'); init();import cloud from 'wx-server-sdk'; cloud.init({ env: 'your-env-id' }); - DB.command
import { command } from 'wx-server-sdk';import cloud from 'wx-server-sdk'; const db = cloud.database(); const _ = db.command;
- Cloud
import * as Cloud from 'wx-server-sdk'; // Use Cloud.init(), Cloud.database(), etc.
Quickstart
import cloud from 'wx-server-sdk';
// Initialize the cloud environment
cloud.init({
env: process.env.WX_CLOUD_ENV_ID ?? '', // Ensure environment ID is configured
traceUser: true, // Enable user tracking for logging
});
const db = cloud.database();
const _ = db.command;
// Cloud Function entry point
export async function main(event: any, context: any) {
try {
// Example: Add a new record to a 'todos' collection
const addResult = await db.collection('todos').add({
data: {
description: 'Learn wx-server-sdk',
completed: false,
createdDate: new Date(),
_openid: event.userInfo.openId, // Automatically available in Cloud Function event
},
});
console.log('Added todo:', addResult);
// Example: Query records from 'todos' collection
const queryResult = await db.collection('todos')
.where({
_openid: event.userInfo.openId,
completed: false,
})
.orderBy('createdDate', 'desc')
.limit(10)
.get();
console.log('Queried todos:', queryResult.data);
// Example: Call another Cloud Function (replace 'anotherFunction' with actual function name)
const callFunctionResult = await cloud.callFunction({
name: 'anotherFunction',
data: { message: 'Hello from main function' },
});
console.log('Called another function:', callFunctionResult.result);
return {
statusCode: 200,
body: 'Operation successful',
addResult,
queryResult: queryResult.data,
callFunctionResult: callFunctionResult.result
};
} catch (e: any) {
console.error('Operation failed:', e);
return {
statusCode: 500,
body: `Operation failed: ${e.message}`,
};
}
}