Wechat cloud hosting WebSocket practice: message push based on template

Posted by yoost on Thu, 20 Jan 2022 12:12:21 +0100

WeChat cloud hosting is a cloud based solution based on cloud based native free operation and high availability services provided by WeChat team Tencent cloud team. It does not need servers, and can deploy small program / official account server in 1 minutes.

PC access https://cloud.weixin.qq.com You can immediately start using wechat cloud hosting, and new users will be given a free quota of 3 months for the first environment.

1, Preparatory work

Step 1: open

Enter WeChat cloud hosting, select small program / official account to login.

Step 2: deploy

At present, wechat cloud hosting provides two deployment modes, threshold free deployment and user-defined deployment. This article will deploy in the door free mode during initialization;

Select a template that you are familiar with and click the "use" button to enter the next step. This article will use the Express template for automatic deployment

Cloud hosting will be automatically deployed according to the template content. If there is a dependent database in the template, the database will be automatically opened during deployment

After successful deployment, the application in the template can be accessed directly through the public domain name, and the calling code fragment is provided

Application of counters provided in the template

2, Start transformation

Step 1: pull code

Official template code portal:


After successful pulling, the directory file is as follows:


Step 2: use websocket related dependencies

In this paper, express WS is used to build websocket service


Step 3: transform the server code

const path = require('path')
const express = require('express')
const cors = require('cors')
const morgan = require('morgan')
const { init: initDB, Counter } = require('./db')

const logger = morgan('tiny')
const app = express();
const expressWs = require('express-ws')(app);
const clients = expressWs.getWss('/').clients
app.ws('/', function (ws, req) { });

app.use(express.urlencoded({ extended: false }))

//Front page
app.get('/', async (req, res) => {

  res.sendFile(path.join(__dirname, 'index.html'))

//Update count
app.post('/api/count', async (req, res) => {
  const { action } = req.body
  if (action === 'inc') {
    await Counter.create()
  } else if (action === 'clear') {
    await Counter.destroy({
      truncate: true
  //Push the results to the client after data changes
  for (let c of clients) {
    c.send(await Counter.count())
    code: 0,
    data: await Counter.count()

//Get count
app.get('/api/count', async (req, res) => {
  const result = await Counter.count()
    code: 0,
    data: result

//Applet call to obtain wechat Open ID
app.get('/api/wx_openid', async (req, res) => {
  if (req.headers['x-wx-source']) {

const port = process.env.PORT || 80

async function bootstrap() {
  await initDB()
  app.listen(port, () => {
    console.log('Start successful', port)


Step 4: deploy the modified code through pipeline (CI/CD)

First, upload the modified code to Gitee/GitHub/GitLab, one of the hosting platforms, and enter wechat cloud hosting service management - > service list - > pipeline - > new pipeline

If the code permission is not authorized or expired, please complete the authorization before creating the pipeline

After the addition is successful, click Start pipeline to trigger the deployment, or check push trigger. When the code is pushed to the specified warehouse, the pipeline will be triggered for code deployment

Tips: because the current template is used in the database, if pipeline triggering is used, the environment variable needs to be configured to container config. json

  "containerPort": 80,
  "dockerfilePath": "Dockerfile",
  "buildDir": "",
  "minNum": 0,
  "maxNum": 10,
  "cpu": 1,
  "mem": 2,
  "policyType": "cpu",
  "policyThreshold": 80,
  "envParams": {
    "MYSQL_ADDRESS": "address",
    "MYSQL_PASSWORD": "password",
    "MYSQL_USERNAME": "user name"
  "customLogs": "stdout",
  "initialDelaySeconds": 2,
  "dataBaseName": "nodejs_demo",
  "executeSQLs": [
    "USE nodejs_demo;"

Step 5: write applet side code

The minimum version of applet base library is 2.21.1

const {
    } = await wx.cloud.connectContainer({
      config: {
        env: '', //Replace your wechat cloud hosting environment ID
      service: '', //Replace your own service name
    socketTask.onMessage(function (res) {
      console.log('[WEBSOCKET]', res.data)
    socketTask.onOpen(function (res) {
      console.log('[WEBSOCKET]', 'Link succeeded!')
      setTimeout(() => {
          data: 'This is an applet message'
      }, 5000);
    socketTask.onClose(function (res) {
      console.log('[WEBSOCKET]Link closed!')

Step 6: start debugging

Open the public network access link for debugging:

Step 7: commissioning results

Now you can see that using the counter template in the web, each click will be transmitted to the applet in real time. In this step, real-time message push is realized through the new WebSocket capability provided by wechat cloud hosting:

3, Summary

The above is the new wechat cloud hosting capability "WebSocket". Based on this new capability, many interesting applications can be extended, such as online chat rooms, collaborative documents, message push, etc. together with some other features of cloud hosting, it is worth experiencing!

Author: Life, senior evangelist of cloud development and cloud hosting. Front end development engineer, familiar with React and node JS, has in-depth research in applet and cloud development, develops multiple sets of commercial applets through cloud development and cloud hosting, and is a lecturer in the live broadcast course of applet · cloud development practical smart wardrobe applet.

Topics: websocket