Skip to main content

Writing HTTP Cloud Functions

"HTTP Cloud Functions" are a type of cloud function specifically designed for web service scenarios, providing native HTTP support and real-time communication capabilities.

💡 About Basic Capabilities: This article focuses on the unique capabilities of HTTP cloud functions (HTTP handling, SSE, WebSocket, etc.). For general capabilities of cloud functions (dependency installation, environment variables, timezone handling, etc.), please refer to Writing Regular Cloud Functions.

Security Warning

Cloud Function and CloudBase Run runtimes can access developer credentials through HTTP headers and environment variables. Handle this sensitive information carefully (including but not limited to the HTTP header x-cloudbase-context and environment variables TENCENTCLOUD_SECRETID/TENCENTCLOUD_SECRETKEY), and avoid directly exposing raw request headers or environment variables to end users. When using services like httpbin that automatically echo request headers back to the caller, be sure to handle this behavior, otherwise significant security risks may arise.

Quick Start

Step 1: Create Function Entry File

Create index.js as the HTTP function entry file. An HTTP cloud function is essentially a standard web service that listens for HTTP requests on port 9000:

const http = require('http');

const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('Hello World!');
});

// The default port for HTTP cloud functions must be 9000
server.listen(9000, '0.0.0.0', () => {
console.log('Server running at http://localhost:9000/');
});

Step 2: Create Bootstrap Script (Required)

Create a scf_bootstrap file (no file extension) in the project root directory with the command to start the project:

#!/bin/bash
node index.js

For details about the bootstrap script, please refer to: Bootstrap File Guide

Project Structure

The complete project directory structure is as follows:

my-web-function/
├── scf_bootstrap # Bootstrap script (required, no extension)
├── package.json # Project configuration
├── index.js # Function entry file
└── node_modules/ # Dependencies (generated after npm install)

Developing with Web Frameworks

HTTP cloud functions support direct development using web frameworks, such as: Express, Koa, NestJS in the Node.js environment, or Flask, Django, FastAPI in the Python environment, or web frameworks in other languages.

Multi-routing is also implemented through web frameworks, for example by defining handlers for different paths via Express's app.get() / app.post() or Flask's @app.route().

Calling CloudBase Resources (SDK Authentication)

When accessing CloudBase resources (database, cloud storage, etc.) via the SDK (@cloudbase/js-sdk or @cloudbase/node-sdk) inside an HTTP Cloud Function, pay special attention to the auth method:

Authentication parameters must be explicitly configured

Unlike event-triggered Cloud Functions, the runtime of an HTTP Cloud Function does NOT inject the TENCENTCLOUD_SECRETID / TENCENTCLOUD_SECRETKEY auth env vars, and the SDK cannot obtain default credentials automatically. Without explicit auth configuration, every API call fails with getCredential failed / secretId or secretKey not found.

When initializing the SDK inside an HTTP Cloud Function, you must explicitly specify one of the following auth methods:

const cloudbase = require("@cloudbase/js-sdk");

// Option 1 (recommended): set CLOUDBASE_APIKEY in the function env vars, then pass accessKey
const app = cloudbase.init({
env: "your-env-id",
accessKey: process.env.CLOUDBASE_APIKEY,
});

// Option 2: explicitly pass the Tencent Cloud key pair
// const app = cloudbase.init({
// env: "your-env-id",
// secretId: "xxx",
// secretKey: "xxx",
// });

For details on auth methods, refer to JS SDK Initialization - Node.js Authentication.

Real-Time Communication Capabilities

HTTP cloud functions provide two real-time communication methods: "SSE (Server-Sent Events)" and "WebSocket".

SSE (Server-Sent Events)

"SSE" is an HTTP-based server push technology that supports unidirectional real-time data streaming (server → client).

Key Features:

  • Based on HTTP protocol, good compatibility, supported by default with no configuration needed
  • Automatic client reconnection
  • Simple implementation, low resource usage
  • Suitable for AI conversation streaming output, real-time logs, progress updates, and similar scenarios

Detailed Documentation: For complete SSE usage guide, message format specifications, and common problem solutions, please refer to SSE Protocol Support.

WebSocket

"WebSocket" is a full-duplex communication protocol that supports bidirectional real-time communication (server ↔ client).

Key Features:

  • Bidirectional real-time communication, persistent connection, low latency
  • Requires enabling WebSocket protocol support in the console
  • Server must listen on port 9000
  • Suitable for real-time chat, collaborative editing, game servers, and similar scenarios

Detailed Documentation: For complete WebSocket usage guide, console configuration steps, usage limits, and common problem solutions, please refer to WebSocket Protocol Support.

Technology Comparison

FeatureSSEWebSocket
CommunicationUnidirectional (server → client)Bidirectional (server ↔ client)
ProtocolHTTPWebSocket protocol
Implementation ComplexitySimpleRelatively complex
Configuration RequirementsNo configuration neededRequires console enablement
Auto ReconnectionYesNo (manual implementation needed)
Use CasesUnidirectional data pushReal-time bidirectional communication

Selection Guide:

  • Only need server-side data push (e.g., AI conversations, logs, progress) → Choose SSE
  • Need bidirectional real-time communication (e.g., chat, collaboration, games) → Choose WebSocket