Migrate from WeChat-native Cloud Development to Standalone CloudBase
In one sentence: Replace
wx.cloudcalls in your WeChat Mini Program's built-in Cloud Development with@cloudbase/js-sdk@2.27.3+ a standalone CloudBase Environment, so the same backend can serve Mini Programs, Web, UniApp, and more.Estimated time: 30–60 minutes (depending on the number of existing
wx.cloudcalls) | Difficulty: Advanced
Applicable Scenarios
- Applicable: Mini Program currently using
wx.cloud.init()built-in Cloud Development and wanting to switch to a standalone CloudBase Environment - Applicable: Wanting the same CloudBase backend to be accessible from Mini Programs, Web, H5, and UniApp simultaneously (
wx.cloudis Mini Program-only) - Applicable: Wanting independent control over environment configuration, billing, and permissions, without being tied to WeChat's Cloud Development Console
- Not applicable: Migrating in from Firebase, Supabase, or other third-party services
Prerequisites
| Dependency | Version |
|---|---|
@cloudbase/js-sdk | 2.27.3 |
@cloudbase/adapter-wx_mp | 1.3.1 |
@cloudbase/node-sdk | 3.18.1 |
@cloudbase/cli | 3.0.4 |
| WeChat DevTools | ≥ 1.06.x |
| Node.js | ≥ 16.13 |
You also need a standalone CloudBase Environment (created at tcb.cloud.tencent.com/dev) with Custom Login enabled.
API Comparison: Before and After
The core database CRUD methods (get, add, update, remove) have the same calling convention in both wx.cloud and @cloudbase/js-sdk — migration only requires swapping the entry-point object. However, the two SDKs differ clearly in initialization, authentication, and file upload parameters.
| Capability | wx.cloud | @cloudbase/js-sdk | Difference |
|---|---|---|---|
| Initialization | wx.cloud.init({ env: 'xxx' }) | cloudbase.useAdapters(adapter); const app = cloudbase.init({ env: 'xxx' }) | Must register the Mini Program adapter |
| Authentication | Automatic (Mini Program login state is bound natively) | Requires Custom Login (signInWithCustomTicket); see Recipe 01 | Biggest difference |
| Database CRUD | wx.cloud.database().collection('x').get() | app.database().collection('x').get() | Method signature compatible — just swap the entry object |
| Cloud Function calls | wx.cloud.callFunction({ name, data }) | app.callFunction({ name, data }) | Parameter structure compatible |
| File upload (client) | wx.cloud.uploadFile({ cloudPath, filePath }) | app.uploadFile({ cloudPath, filePath }) | Client API compatible |
| File upload (Node.js server) | cloud.uploadFile({ cloudPath, fileContent }) | app.uploadFile({ cloudPath, fileContent }) | Compatible; both use fileContent (ReadStream) |
| Security rule context | auth.openid available automatically | User must complete Custom Login first to have an identity context | Rule logic may need adjustment |
Core takeaway: Database and Cloud Function business code barely needs to change. Changes are concentrated in initialization and authentication.
Step 1: Enable Custom Login in the Standalone CloudBase Environment
wx.cloud authentication is silent — the Mini Program login state is bound automatically, and developers don't need to manage it. A standalone CloudBase Environment requires an explicit login; without it, all database and Cloud Function calls will return UNAUTHORIZED.
For WeChat Mini Programs, Custom Login is the recommended approach. The flow is: Mini Program calls wx.login to get a code → Cloud Function exchanges the code for an openid → signs a CloudBase ticket from the openid → Mini Program logs in with the ticket.
The full Custom Login setup is documented in add-auth-wechat-miniprogram and is not repeated here. After completing that setup, you will have:
- A Cloud Function
getLoginTicketthat can issue tickets (with HTTP Access Service enabled) libs/cloudbase.jsandlibs/login.json the Mini Program side
Step 2: Install the New SDK and Replace Initialization Code
cd miniprogram
npm install --save @cloudbase/js-sdk@2.27.3 @cloudbase/adapter-wx_mp@1.3.1
WeChat DevTools → Tools → Build npm.
Then add login logic to app.js inside onLaunch:
import { ensureLogin } from './libs/login';
App({
async onLaunch() {
try {
await ensureLogin();
console.log('[cloudbase] logged in');
} catch (err) {
console.error('[cloudbase] login failed', err);
}
},
});
After this step, all pages can access CloudBase normally in their onLoad handlers.
Step 3: Replace wx.cloud Calls in Business Code One by One
Do a global search for wx.cloud and replace each occurrence.
Database — only swap the entry object:
// ❌ Before migration
const db = wx.cloud.database();
const res = await db.collection('todos').where({ done: false }).get();
// ✅ After migration
import { db } from '../libs/cloudbase';
const res = await db.collection('todos').where({ done: false }).get();
.get() / .add() / .update() / .remove() / .where() / .orderBy() — parameters and return value structures are all compatible; just swap.
Cloud Function calls:
// ❌ Before migration
const res = await wx.cloud.callFunction({
name: 'getProfile',
data: { uid: '123' },
});
// ✅ After migration
import app from '../libs/cloudbase';
const res = await app.callFunction({
name: 'getProfile',
data: { uid: '123' },
});
Note: Cloud Functions in the standalone CloudBase Environment must be deployed separately with tcb fn deploy — functions in the wx.cloud environment do not sync over automatically.
Cloud Storage upload:
// ❌ Before migration
const res = await wx.cloud.uploadFile({
cloudPath: 'images/photo.jpg',
filePath: tempFilePath,
});
// ✅ After migration
import app from '../libs/cloudbase';
const res = await app.uploadFile({
cloudPath: 'images/photo.jpg',
filePath: tempFilePath,
});
Step 4: Migrate Cloud Function Code
wx.cloud Cloud Functions use wx-server-sdk (current npm version 3.0.1); standalone CloudBase uses @cloudbase/node-sdk@3.18.1.
// ❌ wx.cloud Cloud Function
const cloud = require('wx-server-sdk');
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });
const db = cloud.database();
exports.main = async (event, context) => {
return await db.collection('todos').get();
};
// ✅ Standalone CloudBase Cloud Function
const cloudbase = require('@cloudbase/node-sdk');
const app = cloudbase.init({ env: process.env.TCB_ENV });
const db = app.database();
exports.main = async (event, context) => {
return await db.collection('todos').get();
};
Replace the dependency in package.json:
cd cloudfunctions/your-function
npm uninstall wx-server-sdk
npm install --save @cloudbase/node-sdk@3.18.1
Deploy to the standalone environment:
tcb fn deploy your-function --dir ./cloudfunctions/your-function -e your-env-id
Step 5: Migrate Existing Data (if applicable)
If the wx.cloud environment has data you need to carry over:
- WeChat DevTools → Cloud Development Console → Database → Collection → Export (JSON format)
- CloudBase Console → Database → Collection → Import (same JSON file)
Key points to be aware of:
_idfield: CloudBase preserves the original_idon import — it does not generate a new one._openidfield:wx.cloudsecurity rules useauth.openidfor row-level permissions. After migration, the standalone CloudBase identity becomescustomUserId. If your security rules depend on the_openidfield, confirm the identity mapping after migration.- Cloud Storage: Both
wx.cloudand standalone CloudBase fileIDs start withcloud://, but they point to different storage buckets. If business code hardcodes old fileIDs, re-upload those files to the standalone CloudBase storage and update all references. - Large datasets: JSON export has a single-batch size limit. Split into multiple exports for large datasets.
Verification
- WeChat DevTools → Tools → Build npm → Compile
- Confirm
[cloudbase] logged inappears in the Console - Open each page that previously used
wx.cloud— test database read/write, Cloud Function calls, and file upload/download - Spot-check a few records to confirm data is consistent before and after migration
Common Errors
| Symptom | Cause | Fix |
|---|---|---|
All requests return UNAUTHORIZED after migration | ensureLogin() was not called, or Custom Login is not enabled | Confirm app.js calls ensureLogin in onLaunch; confirm Custom Login is enabled in the Console |
| Database queries return empty results | Querying the empty standalone CloudBase database — data not yet imported | Follow Step 5 to import data |
| Old fileIDs return 404 | wx.cloud fileIDs point to the old storage bucket; standalone CloudBase has a different bucket | Re-upload files to standalone CloudBase storage and update references in business code |
Cloud Function calls return FunctionName not found | Cloud Functions not deployed to the standalone CloudBase Environment | Deploy with tcb fn deploy to the target environment |
| Security rules deny access | wx.cloud rules used auth.openid; the identity context changed after migration | Adjust database permission settings in the CloudBase Console to match the new identity |
Related Documentation
- SDK Initialization —
@cloudbase/js-sdk@2.x - WeChat Mini Program Adapter —
@cloudbase/adapter-wx_mp - Custom Login
- WeChat official · Cloud Development docs —
wx.cloudAPI
Next Steps
- Authentication integration details for standalone CloudBase:
add-auth-wechat-miniprogram - Cloud Function cold start optimization:
optimize-cloud-function-wechat-miniprogram