{"id":12681,"library":"wx-server-sdk","title":"WeChat Mini Program Cloud Server SDK","description":"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.","status":"active","version":"3.0.4","language":"javascript","source_language":"en","source_url":null,"tags":["javascript","typescript"],"install":[{"cmd":"npm install wx-server-sdk","lang":"bash","label":"npm"},{"cmd":"yarn add wx-server-sdk","lang":"bash","label":"yarn"},{"cmd":"pnpm add wx-server-sdk","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Internal dependency for interacting with Tencent Cloud Base services, which underpins WeChat Cloud Development.","package":"@cloudbase/node-sdk","optional":false}],"imports":[{"note":"The primary `cloud` object is typically imported as a default export or through `import * as cloud from 'wx-server-sdk;'` for full module access. CommonJS `require` pattern also returns the full `cloud` object.","wrong":"import { cloud } from 'wx-server-sdk';","symbol":"cloud","correct":"import cloud from 'wx-server-sdk';"},{"note":"The `init` function is a method of the main `cloud` object and must be called after importing `cloud`.","wrong":"const { init } = require('wx-server-sdk'); init();","symbol":"init","correct":"import cloud from 'wx-server-sdk'; cloud.init({ env: 'your-env-id' });"},{"note":"Database commands (`db.command`) are accessed via the `db` instance obtained from `cloud.database()`, not directly from the SDK root.","wrong":"import { command } from 'wx-server-sdk';","symbol":"DB.command","correct":"import cloud from 'wx-server-sdk'; const db = cloud.database(); const _ = db.command;"},{"note":"This pattern provides full access to all exported members of the SDK under the `Cloud` namespace, suitable for TypeScript environments or when a single named import is insufficient.","symbol":"Cloud","correct":"import * as Cloud from 'wx-server-sdk'; // Use Cloud.init(), Cloud.database(), etc."}],"quickstart":{"code":"import cloud from 'wx-server-sdk';\n\n// Initialize the cloud environment\ncloud.init({\n  env: process.env.WX_CLOUD_ENV_ID ?? '', // Ensure environment ID is configured\n  traceUser: true, // Enable user tracking for logging\n});\n\nconst db = cloud.database();\nconst _ = db.command;\n\n// Cloud Function entry point\nexport async function main(event: any, context: any) {\n  try {\n    // Example: Add a new record to a 'todos' collection\n    const addResult = await db.collection('todos').add({\n      data: {\n        description: 'Learn wx-server-sdk',\n        completed: false,\n        createdDate: new Date(),\n        _openid: event.userInfo.openId, // Automatically available in Cloud Function event\n      },\n    });\n    console.log('Added todo:', addResult);\n\n    // Example: Query records from 'todos' collection\n    const queryResult = await db.collection('todos')\n      .where({\n        _openid: event.userInfo.openId,\n        completed: false,\n      })\n      .orderBy('createdDate', 'desc')\n      .limit(10)\n      .get();\n    console.log('Queried todos:', queryResult.data);\n\n    // Example: Call another Cloud Function (replace 'anotherFunction' with actual function name)\n    const callFunctionResult = await cloud.callFunction({\n      name: 'anotherFunction',\n      data: { message: 'Hello from main function' },\n    });\n    console.log('Called another function:', callFunctionResult.result);\n\n    return {\n      statusCode: 200,\n      body: 'Operation successful',\n      addResult,\n      queryResult: queryResult.data,\n      callFunctionResult: callFunctionResult.result\n    };\n  } catch (e: any) {\n    console.error('Operation failed:', e);\n    return {\n      statusCode: 500,\n      body: `Operation failed: ${e.message}`,\n    };\n  }\n}","lang":"typescript","description":"This quickstart demonstrates initializing the SDK, performing basic database operations (add and query), and invoking another Cloud Function within a WeChat Cloud Function. It highlights best practices for error handling and accessing user context."},"warnings":[{"fix":"Review any code that serializes BigInt values from database queries or other SDK operations to JSON. Adjust parsing logic to handle BigInts as strings or use custom serialization/deserialization logic if numeric representation is strictly required. For example, convert BigInt to `Number()` if within safe integer limits before JSON.stringify.","message":"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.","severity":"breaking","affected_versions":">=3.0.1"},{"fix":"Implement robust access control policies (ACLs) at the database collection level, use database security rules, and strictly validate all incoming data and user permissions within your Cloud Functions. Never trust client-side input directly.","message":"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.","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"Navigate to your Cloud Function's directory (e.g., `cloudfunctions/myFunction`) and run `npm install --save wx-server-sdk@latest`. Ensure each function requiring the SDK has its own `node_modules` with the dependency.","message":"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.","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"Ensure `cloud.init()` is the first cloud-related call in your Cloud Function's `main` entry point, ideally configuring the `env` parameter with your Cloud Development environment ID (e.g., `cloud.init({ env: 'your-env-id' })`).","message":"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.","severity":"gotcha","affected_versions":">=0.1.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Navigate into the `cloudfunctions/<your-function-name>` directory and run `npm install --save wx-server-sdk`.","cause":"The `wx-server-sdk` package has not been installed in the specific Cloud Function's `node_modules` directory.","error":"Error: Cannot find module 'wx-server-sdk'"},{"fix":"Add `cloud.init({ env: 'your-environment-id' });` at the beginning of your Cloud Function's `main` function.","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`.","error":"TypeError: Cannot read properties of undefined (reading 'database')"},{"fix":"Ensure `db.collection('your_collection_name')` passes a non-empty string as the collection identifier.","cause":"The `collection()` method of the database was called without providing a valid string for the collection name.","error":"Error: 'collection' must be a string"},{"fix":"Declare your Cloud Function's entry point `export async function main(event: any, context: any) { ... }`.","cause":"Using `await` inside a Cloud Function without declaring the function `async`.","error":"SyntaxError: 'await' is only valid in async functions and the top level bodies of modules"}],"ecosystem":"npm"}