Skip to main content

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

FieldRequiredTypeDescription
localPathNoStringLocal path of a single file or folder
cloudPathNoStringCloud path of a single file or folder
filesNoArray<{localPath:string; cloudPath:string}>Array of file information composed of localPath and cloudPath for uploading multiple files
onProgressNoFunctionUpload progress callback event, which is triggered multiple times during the upload process
onFileFinishNo(err, data) => voidCallback after each file is uploaded. If the upload fails, it will callback with err
ignoreNoString 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

FieldTypeDescription
KeyStringObject Key
LastModifiedStringLast modified time of the object, in ISO8601 format, such as 2019-05-24T10:56:40Z date
ETagStringThe 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
SizeStringObject size, unit: bytes
OwnerStringObject owner information
StorageClassStringCOS 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

FieldRequiredTypeDescription
cloudPathRequiredStringCloud path of a file or folder
isDirNoBooleanWhether 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

  • localPath is the path of a local file or folder, in the form of directory/filename, such as ./index.js, static/css/index.css, etc.
  • cloudPath is the path of a file or folder relative to the root directory, in the form of directory/filename, such as index.js, static/css/index.js, etc.
Precautions

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

FieldRequiredTypeDescription
prefixYesStringMatching prefix, restricts the response to only include files (objects) with the specified prefix
markerNoBooleanStarting object key marker. Returns object key entries in UTF-8 lexicographical order after this marker (exclusive).
maxKeysNoBooleanThe maximum number of entries returned in a single response, default is 1000, maximum is 1000

3. Return Results

FieldRequiredTypeDescription
NameYesStringBucket name in the format of \<BucketName-APPID>
PrefixYesStringObject key matching prefix, corresponding to the prefix parameter in the request
MarkerYesStringStarting object key marker. Returns object key entries in UTF-8 lexicographical order after this marker (exclusive), corresponding to the marker parameter in the request
MaxKeysYesNumberThe maximum number of entries returned in a single response, corresponding to the max-keys parameter in the request
ContentsRequiredIContentItemObject entry

IContentItem

FieldRequiredTypeDescription
KeyYesStringObject Key
LastModifiedYesStringLast modified time of the object, in ISO8601 format, such as 2019-05-24T10:56:40Z
ETagYesStringThe 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
SizeYesNumberObject size, unit: bytes
OwnerYesIOwnerInfoObject owner information
StorageClassYesStringCOS storage type. STANDARD_IA, ARCHIVE, etc.

IOwnerInfo

FieldRequiredTypeDescription
IDRequiredStringAPPID of the object owner
DisplayNameYesStringName 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

FieldRequiredTypeDescription
indexDocumentRequiredStringDocument path
errorDocumentOptionalStringDocument path
routingRulesOptionalIRoutingRulesDocument path

IRoutingRules

FieldRequiredTypeDescription
keyPrefixEqualsOptionalStringThe path prefix to redirect, replacing the specified folder/
httpErrorCodeReturnedEqualsOptionalStringSpecifies the redirect error code, only supports configuration of 4XX return codes, and has higher priority than ErrorDocument.
replaceKeyWithOptionalStringReplaces the entire Key with the specified content
replaceKeyPrefixWithOptionalStringReplaces 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

FieldRequiredTypeDescription
statusCodeRequiredNumberThe HTTP status code returned by the request, such as 200, 403, 404, etc.
headersOptionalObjectHeader 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

FieldRequiredTypeDescription
domainRequiredStringCustom domain
certIdRequiredStringCertificate ID

3. Return Results

FieldRequiredTypeDescription
RequestIdRequiredStringRequest 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

FieldRequiredTypeDescription
domainRequiredStringCustom domain

3. Return Results

FieldRequiredTypeDescription
RequestIdRequiredStringRequest 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

FieldRequiredTypeDescription
statusCodeRequiredNumberThe HTTP status code returned by the request, such as 200, 403, 404, etc.
headersRequiredObjectHeader information returned by the request
WebsiteConfigurationYesIWebsiteConfigStatic website configuration

IWebsiteConfig

FieldRequiredTypeDescription
IndexDocumentRequiredIIndexDocumentIndex document
ErrorDocumentRequiredIErrorDocumentError document
RoutingRulesRequiredArray<[IRoutingRule](#IRoutingRule)>Static website configuration

IIndexDocument

FieldRequiredTypeDescription
SuffixRequiredStringSpecify index document

IErrorDocument

FieldRequiredTypeDescription
KeyRequiredStringSpecify generic error return

IRoutingRule

FieldRequiredTypeDescription
ConditionRequiredIConditionTo specify the conditions for redirection to occur. Only one of prefix-based redirection or error code redirection can be specified.
RedirectRequiredIRedirectTo specify the specific replacement rules for redirection when the redirection condition is met

ICondition

FieldRequiredTypeDescription
HttpErrorCodeReturnedEqualsRequiredStringSpecifies the redirect error code, only supports configuration of 4XX return codes, and has higher priority than ErrorDocument.
KeyPrefixEqualsRequiredStringSpecifies the path for prefix-based redirection, replacing the specified folder/

IRedirect

FieldRequiredTypeDescription
ReplaceKeyWithRequiredStringReplaces the entire Key with the specified content
ReplaceKeyPrefixWithRequiredStringReplaces 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

FieldRequiredTypeDescription
domainsRequiredArray<String>List of domains

3. Return Results

FieldRequiredTypeDescription
RecordCountRequiredNumberNumber of recorded domains
RequestIdRequiredStringUnique request ID, returned for every request. Must be provided when troubleshooting issues.
DomainsRequiredArray<[ITcbDomainInfo](#ITcbDomainInfo)>Domain list

ITcbDomainInfo

FieldRequiredTypeDescription
DomainRequiredStringDomain
DomainIdRequiredNumberDomain Id
StatusRequiredStringprocess, online, offline domain status
DomainConfigRequiredITcbDomainConfigDomain configuration
CNameRequiredStringDomain CName

ITcbDomainConfig

FieldRequiredTypeDescription
ReferNoITcbRefererReferer hotlinking protection configuration
CacheOptionalArray<[ITcbCache](#ITcbCache)>Cache policy list
IpFilterNoIIpFilterIP allowlist and blocklist configuration
IpFreqLimitNoIIpFreqLimitIP rate limiting configuration

ITcbReferer

FieldRequiredTypeDescription
SwitchRequiredStringSwitch for referer allowlist and blocklist configuration. on: enable, off: disable
RefererRulesOptionalArray<[ITcbRefererRule](#ITcbRefererRule)>referer allowlist and blocklist configuration rules. Required when switch is on.

ITcbRefererRule

FieldRequiredTypeDescription
RefererTypeRequiredStringreferer configuration type, whitelist: allowlist, blacklist: blocklist
ReferersRequiredArray<String>referer list. The maximum length is 400. Do not include 'http://' prefix. Enter domains in the format: www.test.com
AllowEmptyRequiredBooleanWhether to allow empty referer, true: allow empty referer, false: do not allow empty referer

ITcbCache

FieldRequiredTypeDescription
RuleTypeRequiredStringRule 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.
RuleValueRequiredStringRule 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: ; `
CacheTtlRequiredNumberCache time in seconds. Required.

IIpFilter

FieldRequiredTypeDescription
SwitchRequiredStringSwitch for IP allowlist and blocklist configuration, on: enable, off: disable
FilterTypeNoStringIP allowlist and blocklist type, whitelist: allowlist, blacklist: blocklist
FiltersNoArray<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

FieldRequiredTypeDescription
SwitchRequiredStringIP rate limiting configuration switch, on: enable, off: disable
QpsNoNumberSet 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

FieldRequiredTypeDescription
DomainRequiredStringDomain
DomainIdRequiredNumberDomain Id
DomainConfigRequiredITcbDomainConfigDomain configuration

3. Return Results

FieldRequiredTypeDescription
DomainIdRequiredNumberDomain Id
OriginRequiredITcbOrigincos origin domain
CosPrivateAccessRequiredStringWhether to enable cos private read
AuthenticationRequiredITcbAuthenticationAnti-leech key
CacheRequiredArray<[ITcbCache](#ITcbCache)>Cache policy
StaticWebRequiredITcbStaticStatic website
RootAccessRequiredStringno off, whether to access the root directory
RequestIdRequiredStringUnique request ID, returned for every request

ITcbOrigin

FieldRequiredTypeDescription
MasterRequiredStringMaster site
SlaveNoStringSlave site

ITcbAuthentication

FieldRequiredTypeDescription
SwitchRequiredStringon/off enable or disable'
SecretKeyRequiredStringRequired when enabled. Secret key used to calculate signatures, only supports combinations of letters and digits, 6 to 32 characters.
SignParamNoStringSignature field name in url string, alphanumeric combination, cannot start with a digit, less than 32 characters, defaults to sign
TimeParamNoStringTime field name in url string, alphanumeric combination, cannot start with a digit, less than 32 characters, defaults to t
ExpireTimeNoNumberRequired when enabled. Expiration time, less than 31536000 seconds, in seconds

ITcbStatic

FieldRequiredTypeDescription
SwitchRequiredStringEnable or disable the static website feature.
PathNoStringRedirect 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>

version tip

This API has been supported since v5.0.0.

2. Input Parameters

FieldRequiredTypeDescription
cloudPathRequiredStringCloud file path (relative to the hosting root directory), e.g., images/logo.png
localPathNoStringThe complete local file path for saving, e.g., ./dist/logo.png; returns a readable stream if not passed

3. Return Results

ScenarioReturn TypeDescription
When localPath is passedPromise<string>Returns the local absolute path after the file write operation completes
When localPath is not passedPromise<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>

version tip

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

FieldRequiredTypeDescription
cloudPathRequiredStringCloud directory path, e.g. assets/
localPathNoStringLocal 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()