Functions Framework Quick Start
This article introduces using the @cloudbase/functions-framework framework for development, which provides a more concise functional programming experience.
Prerequisites
Before you begin, make sure you have:
- Have Node.js installed (v18 or later versions recommended)
- Have a Tencent Cloud account with CloudBase service activated
- Have basic knowledge of Node.js development
Step 1: Create a Project Directory
Create a new directory named my-web-function and go to the directory:
mkdir my-web-function
cd my-web-function
Step 2: Initialize Project Configuration
`package.json File:
{
"name": "my-web-function",
"version": "1.0.0",
"main": "index.js",
"dependencies": {
"@cloudbase/functions-framework": "^1.14.0"
}
}
Step 3: Write Sample Code
`index.js File:
exports.main = async function(event, context) {
const { method, path, headers, body } = event;
// Handle different HTTP methods
switch (method) {
case 'GET':
return {
statusCode: 200,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
message: 'Hello from Web Function',
path,
timestamp: new Date().toISOString()
})
};
case 'POST':
return {
statusCode: 201,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
message: 'Data received',
data: JSON.parse(body || '{}')
})
};
default:
return {
statusCode: 405,
body: JSON.stringify({ error: 'Method not allowed' })
};
}
};
Step 4: Write a Startup Script
Create the scf_bootstrap file:
#!/bin/bash
node node_modules/@cloudbase/functions-framework/bin/tcb-ff.js --port=9000 --logDirname=/tmp/logs --interceptOutput=false --extendedContextKey=X-Cloudbase-Context
The scf_bootstrap file must have executable permissions. On Linux/macOS systems, use the chmod +x scf_bootstrap command to set the permissions.
Step 5: Deploy to CloudBase HTTP cloud function
Prepare Deployment Files
Ensure your project directory contains the following files:
my-web-function/
|-- scf_bootstrap
├── package.json
└── index.js
Deploy via the Console
- Log in to the CloudBase Console
- Select your environment and go to the [Cloud Function] page
- Click [New Cloud Function]
- Select [HTTP cloud function]
- Fill in the function name (for example:
helloworld) - Select runtime: Node.js 18.x
- Select the [Local upload] method
- Package the project files into a zip file and upload it
- Click [OK] to complete the deployment
Deploy via CLI
For more details, please refer to CLI Deploy HTTP Function
Package the Project
If you need to package manually, you can use the following command:
# Create zip package
zip -r helloworld.zip package.json index.js
Step 7: Access Your Application
After successful deployment, you can refer to Web Client Invocation to configure custom domain access for
Next Steps
- Learn more about HTTP cloud function configuration options
- Learn how to Add Database Operations