Static Website Hosting
Cloud development (TCB) provides developers with the capability of static website hosting. The distribution of static resources (HTML, CSS, JavaScript, fonts, etc.) is supported by COS and a CDN with multiple edge locations. You can deploy static websites through the Tencent Cloud console for user access. Currently, the static website hosting capability of TCB is only supported in the Tencent Cloud TCB console and is not yet available in the Mini Program IDE console.
uploadFiles
Added in version 3.1.0
1. API Description
API feature: Upload single files, multiple files, and folders to static website hosting
API declaration: async uploadFiles(options: IHostingOptions)
2. Input Parameters
| Field | Required | Type | Description |
|---|---|---|---|
| localPath | No | String | Local path of a single file or folder |
| cloudPath | No | String | Cloud path of a single file or folder |
| files | No | Array<{localPath:string; cloudPath:string}> | Array of file information composed of localPath and cloudPath for uploading multiple files |
| onProgress | No | Function | Upload progress callback event, which is triggered multiple times during the upload process |
| onFileFinish | No | (err, data) => void | Callback after each file is uploaded. If the upload fails, it will callback with err |
| ignore | No | String or Array<String> | File patterns to ignore (glob pattern, e.g., ['**/node_modules/**']) |
When uploading a folder, specify the localPath and cloudPath parameters. All files within the folder will be uploaded to the specified directory, excluding the folder itself.
When uploading multiple files, specify the files parameter.
When cloudPath is empty, files will be uploaded to the root directory.
3. Return Results
4. Sample Code
import CloudBase from '@cloudbase/manager-node'
const { hosting } = new CloudBase({
secretId: 'Your SecretId',
secretKey: 'Your SecretKey',
envId: 'Your envId' // TCB environment ID, which can be obtained from the Tencent Cloud TCB console
})
async function test() {
// Upload folder
await hosting.uploadFiles({
localPath: './dir',
cloudPath: '',
ignore: ['**/ignore.*']
})
let fileCount = 0
// Upload multiple files
await hosting.uploadFiles({
files: [
{
localPath: 'test/storage/test_data/data.txt',
cloudPath: 'hosting/test_data/data.txt'
}
],
ignore: ['**/ignore.*'],
onFileFinish: () => {
fileCount++
}
})
console.log(fileCount) // 1
}
test()
listFiles
Added in version 3.1.0
1. API Description
API feature: Obtain file list
API declaration: async listFiles(): Promise<IListFileInfo[]>
2. Input Parameters
N/A
3. Return Results
| Field | Type | Description |
|---|---|---|
| Key | String | Object Key |
| LastModified | String | Last modified time of the object, in ISO8601 format, such as 2019-05-24T10:56:40Z date |
| ETag | String | The entity tag (Entity Tag) of the object, which is an information tag that identifies the content of the object when it is created and can be used to check whether the content of the object has changed |
| Size | String | Object size, unit: bytes |
| Owner | String | Object owner information |
| StorageClass | String | COS storage type: Standard Storage STANDARD |
4. Code Sample
import CloudBase from '@cloudbase/manager-node'
const { hosting } = new CloudBase({
secretId: 'Your SecretId',
secretKey: 'Your SecretKey',
envId: 'Your envId' // TCB environment ID, which can be obtained from the Tencent Cloud TCB console
})
async function test() {
const res1 = await hosting.listFiles()
for (let item in res1) {
console.log(item)
}
}
test()
deleteFiles
Added in version 3.1.0
1. API Description
API feature: deletes files or folders in static website hosting
API declaration: async deleteFiles(options: IHostingCloudOptions)
2. Parameter Description
| Field | Required | Type | Description |
|---|---|---|---|
| cloudPath | Required | String | Cloud path of a file or folder |
| isDir | No | Boolean | Whether cloudPath is a folder |
3. Return Results
N/A
4. Sample Code
import CloudBase from '@cloudbase/manager-node'
const { hosting } = new CloudBase({
secretId: 'Your SecretId',
secretKey: 'Your SecretKey',
envId: 'Your envId' // TCB environment ID, which can be obtained from the Tencent Cloud TCB console
})
async function test() {
await hosting.deleteFiles({
cloudPath: 'files/data.txt',
isDir: false
})
}
test()
About Path
localPathis the path of a local file or folder, in the form ofdirectory/filename, such as./index.js,static/css/index.css, etc.cloudPathis the path of a file or folder relative to the root directory, in the form ofdirectory/filename, such asindex.js,static/css/index.js, etc.
On Windows systems, localPath is in the local path format recognized by the system, typically using the \ separator. cloudPath is the cloud file path and must use the / separator.
findFiles
Added in version 3.2.0
1. API Description
API feature: Search for files in static website hosting (supports searching by file name prefix)
API declaration: async findFiles(options: IFindOptions)
2. Parameter Description
| Field | Required | Type | Description |
|---|---|---|---|
| prefix | Yes | String | Matching prefix, restricts the response to only include files (objects) with the specified prefix |
| marker | No | Boolean | Starting object key marker. Returns object key entries in UTF-8 lexicographical order after this marker (exclusive). |
| maxKeys | No | Boolean | The maximum number of entries returned in a single response, default is 1000, maximum is 1000 |
3. Return Results
| Field | Required | Type | Description |
|---|---|---|---|
| Name | Yes | String | Bucket name in the format of \<BucketName-APPID> |
| Prefix | Yes | String | Object key matching prefix, corresponding to the prefix parameter in the request |
| Marker | Yes | String | Starting object key marker. Returns object key entries in UTF-8 lexicographical order after this marker (exclusive), corresponding to the marker parameter in the request |
| MaxKeys | Yes | Number | The maximum number of entries returned in a single response, corresponding to the max-keys parameter in the request |
| Contents | Required | IContentItem | Object entry |
IContentItem
| Field | Required | Type | Description |
|---|---|---|---|
| Key | Yes | String | Object Key |
| LastModified | Yes | String | Last modified time of the object, in ISO8601 format, such as 2019-05-24T10:56:40Z |
| ETag | Yes | String | The entity tag (Entity Tag) of the object, which is an information tag that identifies the content of the object when it is created, and can be used to check whether the content of the object has changed |
| Size | Yes | Number | Object size, unit: bytes |
| Owner | Yes | IOwnerInfo | Object owner information |
| StorageClass | Yes | String | COS storage type. STANDARD_IA, ARCHIVE, etc. |
IOwnerInfo
| Field | Required | Type | Description |
|---|---|---|---|
| ID | Required | String | APPID of the object owner |
| DisplayName | Yes | String | Name of the object owner |
4. Sample Code
import CloudBase from '@cloudbase/manager-node'
const { hosting } = new CloudBase({
secretId: 'Your SecretId',
secretKey: 'Your SecretKey',
envId: 'Your envId' // TCB environment ID, which can be obtained from the Tencent Cloud TCB console
})
async function test() {
const { Contents } = await hosting.findFiles({
prefix: 'hosting/',
marker: '/'
})
console.log(Contents)
}
test()
setWebsiteDocument
Added in version 3.2.0
1. API Description
API feature: Configure the error document, index document, and redirect rules for static websites
API declaration: async setWebsiteDocument(options: IBucketWebsiteOptiosn)
2. Parameter Description
| Field | Required | Type | Description |
|---|---|---|---|
| indexDocument | Required | String | Document path |
| errorDocument | Optional | String | Document path |
| routingRules | Optional | IRoutingRules | Document path |
IRoutingRules
| Field | Required | Type | Description |
|---|---|---|---|
| keyPrefixEquals | Optional | String | The path prefix to redirect, replacing the specified folder/ |
| httpErrorCodeReturnedEquals | Optional | String | Specifies the redirect error code, only supports configuration of 4XX return codes, and has higher priority than ErrorDocument. |
| replaceKeyWith | Optional | String | Replaces the entire Key with the specified content |
| replaceKeyPrefixWith | Optional | String | Replaces the matched prefix with the specified content, and can only be set when KeyPrefixEquals is configured |
Note: When configuring the prefix match keyPrefixEquals, the replacement content can be specified as replaceKeyWith (replaces the entire path) or replaceKeyPrefixWith (replaces the prefix). When configuring the specified redirect error code httpErrorCodeReturnedEquals, only replaceKeyWith (replaces the entire path) can be specified.
3. Return Results
| Field | Required | Type | Description |
|---|---|---|---|
| statusCode | Required | Number | The HTTP status code returned by the request, such as 200, 403, 404, etc. |
| headers | Optional | Object | Header information returned by the request |
4. Sample Code
import CloudBase from '@cloudbase/manager-node'
const { hosting } = new CloudBase({
secretId: 'Your SecretId',
secretKey: 'Your SecretKey',
envId: 'Your envId' // TCB environment ID, which can be obtained from the Tencent Cloud TCB console
})
async function test() {
const res = await hosting.setWebsiteDocument({
errorDocument: 'error.html',
indexDocument: 'success.html',
routingRules: [
{
keyPrefixEquals: 'test.html',
replaceKeyWith: 'index.html'
},
{
keyPrefixEquals: 'test1.html',
replaceKeyPrefixWith: 'index1.html'
},
{
httpErrorCodeReturnedEquals: '400',
replaceKeyWith: 'index.html'
}
]
})
if (res.statusCode === 200) {
// todo
}
}
test()
CreateHostingDomain
Added in version 3.2.0
1. API Description
API feature: Bind custom domains
API declaration: async CreateHostingDomain(options: IBindDomainOptions)
2. Parameter Description
| Field | Required | Type | Description |
|---|---|---|---|
| domain | Required | String | Custom domain |
| certId | Required | String | Certificate ID |
3. Return Results
| Field | Required | Type | Description |
|---|---|---|---|
| RequestId | Required | String | Request ID |
4. Sample Code
import CloudBase from '@cloudbase/manager-node'
const { hosting } = new CloudBase({
secretId: 'Your SecretId',
secretKey: 'Your SecretKey',
envId: 'Your envId' // TCB environment ID, which can be obtained from the Tencent Cloud TCB console
})
async function test() {
const res = await hosting.CreateHostingDomain({
domain: 'xxx.xxx.xxx',
certId: 'xxxxx'
})
console.log(res)
}
test()
deleteHostingDomain
Added in version 3.3.0
1. API Description
API feature: Unbind custom domains
API declaration: async deleteHostingDomain(options: IDeleteDomainOptions)
2. Parameter Description
| Field | Required | Type | Description |
|---|---|---|---|
| domain | Required | String | Custom domain |
3. Return Results
| Field | Required | Type | Description |
|---|---|---|---|
| RequestId | Required | String | Request ID |
4. Sample Code
import CloudBase from '@cloudbase/manager-node'
const { hosting } = new CloudBase({
secretId: 'Your SecretId',
secretKey: 'Your SecretKey',
envId: 'Your envId' // TCB environment ID, which can be obtained from the Tencent Cloud TCB console
})
async function test() {
const res = await hosting.deleteHostingDomain({
domain: 'xxx.xxx.xxx'
})
console.log(res)
}
test()
getWebsiteConfig
Added in version 3.3.0
1. API Description
Feature: Obtain static website configuration
API declaration: async getWebsiteConfig()
2. Parameter Description
N/A
3. Return Results
| Field | Required | Type | Description |
|---|---|---|---|
| statusCode | Required | Number | The HTTP status code returned by the request, such as 200, 403, 404, etc. |
| headers | Required | Object | Header information returned by the request |
| WebsiteConfiguration | Yes | IWebsiteConfig | Static website configuration |
IWebsiteConfig
| Field | Required | Type | Description |
|---|---|---|---|
| IndexDocument | Required | IIndexDocument | Index document |
| ErrorDocument | Required | IErrorDocument | Error document |
| RoutingRules | Required | Array<[IRoutingRule](#IRoutingRule)> | Static website configuration |
IIndexDocument
| Field | Required | Type | Description |
|---|---|---|---|
| Suffix | Required | String | Specify index document |
IErrorDocument
| Field | Required | Type | Description |
|---|---|---|---|
| Key | Required | String | Specify generic error return |
IRoutingRule
| Field | Required | Type | Description |
|---|---|---|---|
| Condition | Required | ICondition | To specify the conditions for redirection to occur. Only one of prefix-based redirection or error code redirection can be specified. |
| Redirect | Required | IRedirect | To specify the specific replacement rules for redirection when the redirection condition is met |
ICondition
| Field | Required | Type | Description |
|---|---|---|---|
| HttpErrorCodeReturnedEquals | Required | String | Specifies the redirect error code, only supports configuration of 4XX return codes, and has higher priority than ErrorDocument. |
| KeyPrefixEquals | Required | String | Specifies the path for prefix-based redirection, replacing the specified folder/ |
IRedirect
| Field | Required | Type | Description |
|---|---|---|---|
| ReplaceKeyWith | Required | String | Replaces the entire Key with the specified content |
| ReplaceKeyPrefixWith | Required | String | Replaces the matched prefix with the specified content, and can only be set when Conditon is KeyPrefixEquals |
4. Sample Code
import CloudBase from '@cloudbase/manager-node'
const { hosting } = new CloudBase({
secretId: 'Your SecretId',
secretKey: 'Your SecretKey',
envId: 'Your envId' // TCB environment ID, which can be obtained from the Tencent Cloud TCB console
})
async function test() {
const getConfig = await hosting.getWebsiteConfig()
console.log('getConfig :', getConfig)
}
test()
tcbCheckResource
Added in version 3.3.0
1. API Description
API Feature: Obtain Domain Configuration
API declaration: async tcbCheckResource(options: ICheckSourceOptions)
2. Parameter Description
| Field | Required | Type | Description |
|---|---|---|---|
| domains | Required | Array<String> | List of domains |
3. Return Results
| Field | Required | Type | Description |
|---|---|---|---|
| RecordCount | Required | Number | Number of recorded domains |
| RequestId | Required | String | Unique request ID, returned for every request. Must be provided when troubleshooting issues. |
| Domains | Required | Array<[ITcbDomainInfo](#ITcbDomainInfo)> | Domain list |
ITcbDomainInfo
| Field | Required | Type | Description |
|---|---|---|---|
| Domain | Required | String | Domain |
| DomainId | Required | Number | Domain Id |
| Status | Required | String | process, online, offline domain status |
| DomainConfig | Required | ITcbDomainConfig | Domain configuration |
| CName | Required | String | Domain CName |
ITcbDomainConfig
| Field | Required | Type | Description |
|---|---|---|---|
| Refer | No | ITcbReferer | Referer hotlinking protection configuration |
| Cache | Optional | Array<[ITcbCache](#ITcbCache)> | Cache policy list |
| IpFilter | No | IIpFilter | IP allowlist and blocklist configuration |
| IpFreqLimit | No | IIpFreqLimit | IP rate limiting configuration |
ITcbReferer
| Field | Required | Type | Description |
|---|---|---|---|
| Switch | Required | String | Switch for referer allowlist and blocklist configuration. on: enable, off: disable |
| RefererRules | Optional | Array<[ITcbRefererRule](#ITcbRefererRule)> | referer allowlist and blocklist configuration rules. Required when switch is on. |
ITcbRefererRule
| Field | Required | Type | Description |
|---|---|---|---|
| RefererType | Required | String | referer configuration type, whitelist: allowlist, blacklist: blocklist |
| Referers | Required | Array<String> | referer list. The maximum length is 400. Do not include 'http://' prefix. Enter domains in the format: www.test.com |
| AllowEmpty | Required | Boolean | Whether to allow empty referer, true: allow empty referer, false: do not allow empty referer |
ITcbCache
| Field | Required | Type | Description |
|---|---|---|---|
| RuleType | Required | String | Rule type: all (all files), suffix (match by suffix), path (match by directory for folder type), file (full path matching). Select one from the four options. |
| RuleValue | Required | String | Rule content varies by rule type. Separate entries with ';'. Required. For suffix type, each suffix must not exceed 10 bytes, total length ≤512 bytes. For file type, cannot start with '/' or end with '/'. For path type, cannot contain characters: ; ` |
| CacheTtl | Required | Number | Cache time in seconds. Required. |
IIpFilter
| Field | Required | Type | Description |
|---|---|---|---|
| Switch | Required | String | Switch for IP allowlist and blocklist configuration, on: enable, off: disable |
| FilterType | No | String | IP allowlist and blocklist type, whitelist: allowlist, blacklist: blocklist |
| Filters | No | Array<String> | IP allowlist and blocklist. Supports IP addresses in X.X.X.X format or subnets in /8, /16, /24 format. You can add up to 50 allowlists or 50 blocklists. |
IIpFreqLimit
| Field | Required | Type | Description |
|---|---|---|---|
| Switch | Required | String | IP rate limiting configuration switch, on: enable, off: disable |
| Qps | No | Number | Set the requests per second limit. Requests exceeding the limit will directly return 514. |
4. Sample Code
import CloudBase from '@cloudbase/manager-node'
const { hosting } = new CloudBase({
secretId: 'Your SecretId',
secretKey: 'Your SecretKey',
envId: 'Your envId' // TCB environment ID, which can be obtained from the Tencent Cloud TCB console
})
async function test() {
const res = await hosting.tcbCheckResource({
domains: ['domain']
})
console.log('res:', res)
}
test()
tcbModifyAttribute
Added in version 3.3.0
1. API Description
API Feature: Domain Configuration
API declaration: async tcbModifyAttribute(options: IModifyOptions)
2. Parameter Description
| Field | Required | Type | Description |
|---|---|---|---|
| Domain | Required | String | Domain |
| DomainId | Required | Number | Domain Id |
| DomainConfig | Required | ITcbDomainConfig | Domain configuration |
3. Return Results
| Field | Required | Type | Description |
|---|---|---|---|
| DomainId | Required | Number | Domain Id |
| Origin | Required | ITcbOrigin | cos origin domain |
| CosPrivateAccess | Required | String | Whether to enable cos private read |
| Authentication | Required | ITcbAuthentication | Anti-leech key |
| Cache | Required | Array<[ITcbCache](#ITcbCache)> | Cache policy |
| StaticWeb | Required | ITcbStatic | Static website |
| RootAccess | Required | String | no off, whether to access the root directory |
| RequestId | Required | String | Unique request ID, returned for every request |
ITcbOrigin
| Field | Required | Type | Description |
|---|---|---|---|
| Master | Required | String | Master site |
| Slave | No | String | Slave site |
ITcbAuthentication
| Field | Required | Type | Description |
|---|---|---|---|
| Switch | Required | String | on/off enable or disable' |
| SecretKey | Required | String | Required when enabled. Secret key used to calculate signatures, only supports combinations of letters and digits, 6 to 32 characters. |
| SignParam | No | String | Signature field name in url string, alphanumeric combination, cannot start with a digit, less than 32 characters, defaults to sign |
| TimeParam | No | String | Time field name in url string, alphanumeric combination, cannot start with a digit, less than 32 characters, defaults to t |
| ExpireTime | No | Number | Required when enabled. Expiration time, less than 31536000 seconds, in seconds |
ITcbStatic
| Field | Required | Type | Description |
|---|---|---|---|
| Switch | Required | String | Enable or disable the static website feature. |
| Path | No | String | Redirect path for static website, must start with /, and cannot contain spaces or characters `; |
4. Sample Code
import CloudBase from '@cloudbase/manager-node'
const { hosting } = new CloudBase({
secretId: 'Your SecretId',
secretKey: 'Your SecretKey',
envId: 'Your envId' // TCB environment ID, which can be obtained from the Tencent Cloud TCB console
})
async function test() {
const res = await hosting.tcbCheckResource({
domains: ['domain']
})
const domainId = res.Domains[0].DomainId
const setRes = await hosting.tcbModifyAttribute({
domain: 'domain',
domainId,
domainConfig: {
Refer: {
Switch: 'on',
RefererRules: [
{
AllowEmpty: false,
RefererType: 'blacklist',
Referers: ['www.test11.com']
}
]
},
IpFilter: {
Switch: 'on',
FilterType: 'blacklist',
Filters: ['xxx.xxx.xxx.xxx']
},
IpFreqLimit: {
Switch: 'on',
Qps: 100
},
Cache: [
{
RuleType: 'suffix',
RuleValue: '.jpg',
CacheTtl: 60
}
]
}
})
console.log('setRes:', setRes)
}
test()
downloadFile
1. API Description
API feature: Download a single file from static hosting to the local device, or return a readable stream
API declaration: app.hosting.downloadFile(options): Promise<NodeJS.ReadableStream | string>
This API has been supported since v5.0.0.
2. Input Parameters
| Field | Required | Type | Description |
|---|---|---|---|
| cloudPath | Required | String | Cloud file path (relative to the hosting root directory), e.g., images/logo.png |
| localPath | No | String | The complete local file path for saving, e.g., ./dist/logo.png; returns a readable stream if not passed |
3. Return Results
| Scenario | Return Type | Description |
|---|---|---|
When localPath is passed | Promise<string> | Returns the local absolute path after the file write operation completes |
When localPath is not passed | Promise<NodeJS.ReadableStream> | Returns a readable stream that can be consumed by the user |
4. Sample Code
const CloudBase = require('@cloudbase/manager-node')
const app = new CloudBase({ secretId: 'Your SecretId', secretKey: 'Your SecretKey', envId: 'your-env-id' })
async function test() {
// Download to local file
const localPath = await app.hosting.downloadFile({
cloudPath: 'images/logo.png',
localPath: './dist/logo.png'
})
console.log('File saved to:', localPath)
// Obtain the readable stream (handle it yourself)
const stream = await app.hosting.downloadFile({
cloudPath: 'data/report.csv'
})
stream.pipe(process.stdout)
}
test()
downloadDirectory
1. API Description
API feature: batch download all files from the cloud directory to local
API declaration: app.hosting.downloadDirectory(options): Promise<void>
This API has been supported since v5.0.0.
The internal concurrency is 20, and the underlying layer reuses downloadFile. Empty directories and path entries are automatically skipped.
2. Input Parameters
| Field | Required | Type | Description |
|---|---|---|---|
| cloudPath | Required | String | Cloud directory path, e.g. assets/ |
| localPath | No | String | Local target directory path; the directory will be created automatically if it does not exist; if not passed, the current working directory will be used as the root |
3. Return Results
Promise<void> — resolves after all files are downloaded.
4. Sample Code
async function test() {
await app.hosting.downloadDirectory({
cloudPath: 'assets/',
localPath: './local-assets'
})
console.log('Directory download completed')
}
test()