Skip to main content

Writing HTTP Cloud Functions

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

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

Quick Start

Step 1: Create Function Entry File

Create index.js as the HTTP function entry file:

exports.main = function (event, context) {
return `Hello world!`;
};

Step 2: Create Startup Script (Required)

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

#!/bin/bash
node index.js

For startup script details, please refer to: Startup File Documentation

Project Structure

The complete project directory structure is as follows:

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

Reference Resources:

💡 Tip: HTTP cloud functions support "function routing" functionality, allowing multiple sub-functions to run on the same instance. See HTTP Cloud Function Routing for details.

Function Structure and Parameters

Basic Structure

exports.main = function (event, context) {
// Function logic
};

Or use async function:

exports.main = async function (event, context) {
// Async function logic
};

💡 Type Definition Support: CloudBase provides the @cloudbase/functions-typings@v-1 type definition package to assist with TypeScript code writing. See the Writing Functions with TypeScript section for details.

event Parameter

The event parameter contains HTTP request data, with content varying based on request type:

  • POST request: Request body content
  • multipart/form-data: Form data
  • PUT request: Uploaded files
  • No request body: Empty object {}

context Parameter

The context parameter provides contextual information about function execution:

Property/MethodTypeDescription
eventIDstringUnique event identifier for correlating requests
eventTypestringEvent type, fixed as http
timestampnumberRequest timestamp
httpContexthttpBasisHTTP request related information
extendedContextRecord<string, unknown>Extended context information (environment info)

httpBasis Interface:

PropertyTypeDescription
urlstringComplete URL of this request
httpMethodstringHTTP method (e.g., GET, POST)
headersIncomingHttpHeadersHTTP request headers

extendedContext Extended Information:

// import { TcbExtendedContext } from '@cloudbase/functions-typings'
interface TcbExtendedContext {
envId: string; // Environment ID
uin: string; // Request UIN
source: string; // Request source (e.g., wx)
serviceName: string; // Service name
serviceVersion: string; // Service version
authMethod?: string; // Authentication method: UNAUTHORIZED | CAM_TC3 | TCB_OAUTH2_B | TCB_OAUTH2_C | WX_SERVER_AUTH
userType?: string; // User type: NONE | B_SIDE_USER | C_SIDE_USER
isAdministrator?: boolean; // Whether C-side user is administrator
accessToken?: string; // AccessToken used in the request
userId?: string; // User ID of the request
tmpSecret?: {
// Temporary credentials
secretId: string;
secretKey: string;
token: string;
};
wechatContext?: {
// WeChat context information
callId: string; // WeChat call ID
source: string; // Request source
appId: string; // Mini Program AppID
openId: string; // User OpenID
unionId: string; // User UnionID
fromOpenId?: string; // fromOpenID when sharing environment resources
fromUnionId?: string; // fromUnionID when sharing environment resources
fromAppId?: string; // fromAppID when sharing environment resources
};
}

Function Routing

HTTP cloud functions support web frameworks, so you can implement multiple routes through the corresponding web framework.

It can also be implemented based on the @cloudbase/functions-framework framework. It supports splitting a large function into multiple sub-functions and routing different requests to different handler functions through request paths.

Please refer to: HTTP Cloud Function Routing

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 stream transmission (server → client).

Core Features:

  • Based on HTTP protocol, good compatibility, supported by default without configuration
  • Client automatic 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).

Core 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 limitations, and common problem solutions, please refer to WebSocket Protocol Support.

Technology Selection Comparison

FeatureSSEWebSocket
Communication ModeUnidirectional (server→client)Bidirectional (server↔client)
ProtocolHTTPWebSocket protocol
ImplementationSimpleRelatively complex
ConfigurationNo configuration requiredConsole activation required
Auto-reconnectYesNo (manual implementation)
Use CasesUnidirectional data pushReal-time bidirectional communication

Selection Recommendations:

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

Writing Function Code with TypeScript

Type Definition Installation

npm install @cloudbase/functions-typings@v-1

Basic Type Definition

import { TcbEventFunction } from '@cloudbase/functions-typings';

TcbEventFunction is a generic type:

TcbEventFunction<EventT = unknown, ResultT extends ReturnT = void>
  • EventT: Defines the event parameter type
  • ResultT: Defines the function return value type

Defining event Parameter Type

JSON Request Body:

type JsonEvent = { a: number; b: string; c: boolean };

export const main: TcbEventFunction<JsonEvent> = function (event, context) {
event.a; // number
event.b; // string
};

FormData File Upload:

import { TcbEventFunction, File } from '@cloudbase/functions-typings';

type FormEvent = { str: string; file: File };

export const main: TcbEventFunction<FormEvent> = function (event, context) {
event.str;
event.file.filepath;
};

Defining Return Value Type

Regular Response:

export const main: TcbEventFunction<void, string> = function (event, context) {
return 'done.';
};

Integrated Response:

import { TcbEventFunction, IntegrationResponse } from '@cloudbase/functions-typings';

export const main: TcbEventFunction<void, IntegrationResponse<string>> = function (event, context) {
return {
statusCode: 200,
headers: {},
body: 'Hello world',
};
};

Async Function:

export const main: TcbEventFunction<void, Promise<string>> = async function (event, context) {
return new Promise((resolve) => {
setImmediate(() => {
resolve('done.');
});
});
};

Complete Examples

import { TcbEventFunction, File, IntegrationResponse } from '@cloudbase/functions-typings';

// GET without request body
export const main: TcbEventFunction = function (event, context) {};

// JSON request body
type JsonEvent = { a: number; b: string };
export const main: TcbEventFunction<JsonEvent> = function (event, context) {
event.a;
event.b;
};

// FormData upload
type FormEvent = { str: string; file: File };
export const main: TcbEventFunction<FormEvent> = function (event, context) {
event.str;
event.file.filepath;
};

// Binary stream
export const main: TcbEventFunction<Buffer> = function (event, context) {
event.byteLength;
};

// Accessing Context information
export const main: TcbEventFunction<void, void> = function (event, context) {
context.extendedContext?.envId;
context.extendedContext?.userId;
};

// Regular response
export const main: TcbEventFunction<void, string> = function (event, context) {
return 'done.';
};

// Integrated response
export const main: TcbEventFunction<void, IntegrationResponse<string>> = function (event, context) {
return {
statusCode: 200,
headers: {},
body: '',
};
};

// Async function
export const main: TcbEventFunction<void, Promise<string>> = async function (event, context) {
return new Promise((resolve) => {
setImmediate(() => {
resolve('done.');
});
});
};

// SSE
export const main: TcbEventFunction<void, Promise<string>> = async function (event, context) {
const sse = context.sse?.();

if (sse && !sse.closed) {
sse.on('close', () => {
console.log('sse closed');
});

sse.send({ data: 'hello from sse function' });

sse.send([{ data: 'This is the first message.' }, { data: 'This is the second message.' }]);
}
return '';
};

// WebSocket
export const main: TcbEventFunction = async function (event, context) {
if (context.ws) {
context.ws.on('open', (msg) => {
console.log('open: ', msg);
});
context.ws.on('error', (msg) => {
console.log('error: ', msg);
});
context.ws.on('close', (msg) => {
console.log('close: ', msg);
});
context.ws.on('message', (msg) => {
console.log('message: ', msg);
});
context.ws.send('hello from websocket function');
}
};
main.handleUpgrade = async function (context) {
return {
allowWebSocket: true,
};
};

Project Organization Structure

TypeScript-based Multi-function Project

.
├── README.md
├── Dockerfile
├── src/
│ ├── func-a/
│ │ ├── built/ # Compiled code
│ │ ├── src/ # TypeScript source code
│ │ ├── package.json
│ │ ├── cloudbase-functions.json
│ │ └── tsconfig.json
│ └── func-b/
│ ├── built/
│ ├── src/
│ ├── package.json
│ └── tsconfig.json
├── package.json
└── tsconfig.json

Project structure reference: TypeScript Template Project

Single Function Project

.
├── README.md
├── built/ # Compiled code
├── src/ # TypeScript source code
├── Dockerfile
├── package.json
├── cloudbase-functions.json
└── tsconfig.json

💡 Tip: JavaScript projects do not need src, built, tsconfig.json directories and files.