Skip to main content

Migrate from WeChat-native Cloud Development to Standalone CloudBase

In one sentence: Replace wx.cloud calls 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.cloud calls) | 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.cloud is 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

DependencyVersion
@cloudbase/js-sdk2.27.3
@cloudbase/adapter-wx_mp1.3.1
@cloudbase/node-sdk3.18.1
@cloudbase/cli3.0.4
WeChat DevTools1.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.

Capabilitywx.cloud@cloudbase/js-sdkDifference
Initializationwx.cloud.init({ env: 'xxx' })cloudbase.useAdapters(adapter); const app = cloudbase.init({ env: 'xxx' })Must register the Mini Program adapter
AuthenticationAutomatic (Mini Program login state is bound natively)Requires Custom Login (signInWithCustomTicket); see Recipe 01Biggest difference
Database CRUDwx.cloud.database().collection('x').get()app.database().collection('x').get()Method signature compatible — just swap the entry object
Cloud Function callswx.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 contextauth.openid available automaticallyUser must complete Custom Login first to have an identity contextRule 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 getLoginTicket that can issue tickets (with HTTP Access Service enabled)
  • libs/cloudbase.js and libs/login.js on 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:

  1. WeChat DevTools → Cloud Development Console → Database → Collection → Export (JSON format)
  2. CloudBase Console → Database → Collection → Import (same JSON file)

Key points to be aware of:

  • _id field: CloudBase preserves the original _id on import — it does not generate a new one.
  • _openid field: wx.cloud security rules use auth.openid for row-level permissions. After migration, the standalone CloudBase identity becomes customUserId. If your security rules depend on the _openid field, confirm the identity mapping after migration.
  • Cloud Storage: Both wx.cloud and standalone CloudBase fileIDs start with cloud://, 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

  1. WeChat DevTools → Tools → Build npm → Compile
  2. Confirm [cloudbase] logged in appears in the Console
  3. Open each page that previously used wx.cloud — test database read/write, Cloud Function calls, and file upload/download
  4. Spot-check a few records to confirm data is consistent before and after migration

Common Errors

SymptomCauseFix
All requests return UNAUTHORIZED after migrationensureLogin() was not called, or Custom Login is not enabledConfirm app.js calls ensureLogin in onLaunch; confirm Custom Login is enabled in the Console
Database queries return empty resultsQuerying the empty standalone CloudBase database — data not yet importedFollow Step 5 to import data
Old fileIDs return 404wx.cloud fileIDs point to the old storage bucket; standalone CloudBase has a different bucketRe-upload files to standalone CloudBase storage and update references in business code
Cloud Function calls return FunctionName not foundCloud Functions not deployed to the standalone CloudBase EnvironmentDeploy with tcb fn deploy to the target environment
Security rules deny accesswx.cloud rules used auth.openid; the identity context changed after migrationAdjust database permission settings in the CloudBase Console to match the new identity

Next Steps

  • Authentication integration details for standalone CloudBase: add-auth-wechat-miniprogram
  • Cloud Function cold start optimization: optimize-cloud-function-wechat-miniprogram