Tencent Cloud EdgeOne

Tencent Cloud EdgeOne
Edge Functions
Product Documentation©2013-2022 Tencent Cloud. All rights reserved.

Page 1 of 360

Tencent Cloud EdgeOne

Copyright Notice©2013-2024 Tencent Cloud. All rights reserved.
Copyright in this document is exclusively owned by Tencent Cloud. You must not reproduce, modify, copy or distributein any way, in whole or in part, the contents of this document without Tencent Cloud's the prior written consent.
Trademark Notice

All trademarks associated with Tencent Cloud and its services are owned by Tencent Cloud Computing (Beijing)
Company Limited and its affiliated companies. Trademarks of third parties referred to in this document are owned bytheir respective proprietors.
Service Statement
This document is intended to provide users with general information about Tencent Cloud's products and services
only and does not form part of Tencent Cloud's terms and conditions. Tencent Cloud's products or services are
subject to change. Specific products and services and the standards applicable to them are exclusively provided for in
Tencent Cloud's applicable terms and conditions.

©2013-2022 Tencent Cloud. All rights reserved.

Page 2 of 360

Tencent Cloud EdgeOne

Contents
Edge Functions
Overview
Getting Started
Operation Guide
Function Management
Function Trigger
Environment Variable
Runtime APIs
addEventListener
Cache
Cookies
Encoding
Fetch
FetchEvent
Headers
RequestResponse
Streams
ReadableStream
ReadableStreamBYOBReader
ReadableStreamDefaultReader
TransformStream
WritableStream
WritableStreamDefaultWriter
Web Crypto
Web standards
ImagesImageProperties
Sample Functions
Returning an HTML Page
Returning a JSON Object
Fetch Remote Resources
Authenticating a Request Header
Modifying a Response Header
Performing an A/B Test

©2013-2022 Tencent Cloud. All rights reserved.

Page 3 of 360

Tencent Cloud EdgeOne

Setting Cookies
Performing Redirect Based on the Request Location
Using the Cache API
Caching POST Requests
Responding in Streaming Mode
Merging Resources and Responding in Streaming Mode
Protecting Data from Tampering
Rewriting a m3u8 File and Configuring Authentication
Adaptive Image Resize
Image Adaptive WebP
Customize Referer restriction rules
Remote Authentication
HMAC Digital Signature
Naming a Downloaded File
Obtaining Client IP Address
Best Practices
Adaptive Image Format Conversion via Edge Functions©2013-2022 Tencent Cloud. All rights reserved.

Page 4 of 360

Tencent Cloud EdgeOne

Edge Functions
Overview：

Last updated 2024-07-16 10:17:02
Tencent Cloud Edge Functions provides a serverless code execution environment for the edge nodes of Tencent
Cloud EdgeOne. This way, you can focus on writing business function code and configuring triggering rules, without
the need to configure or manage infrastructure such as servers. The written code can be elastically and securely
executed on the edge nodes that are closest to users.

How It Works©2013-2022 Tencent Cloud. All rights reserved.

Page 5 of 360

Tencent Cloud EdgeOne

You can develop JavaScript functions and deploy them to the edge nodes of Tencent Cloud EdgeOne.
1. If a client request does not hit the configured function triggering rule, the request is handled in the following process:(1) The client request is sent to the gateway of an edge node of Tencent Cloud EdgeOne. > (2) The cache of
the node responds if the requested content already exists in the cache. > (3) The origin server responds if therequested content does not exist in the cache.
2. If a client request hits the configured function triggering rule, the request is handled in one of the following
processes:(1) The client request is sent to the gateway of an edge node of Tencent Cloud EdgeOne. > (4) Edge
Functions receives and executes the JavaScript code. > (5) Subrequests access the cache. > (3) The origin
server responds if the requested content does not exist in the cache.
(1) The client request is sent to the gateway of an edge node of Tencent Cloud EdgeOne. > (4) Edge
Functions receives and executes the JavaScript code. > (6) Subrequests access the public network service.

Benefits©2013-2022 Tencent Cloud. All rights reserved.

Page 6 of 360

Tencent Cloud EdgeOne

Distributed Deployment
Tencent Cloud EdgeOne supports more than 3,200 edge nodes. Edge Functions is deployed on edge nodes in
distributed mode.
Ultra-low Latency
Client requests are automatically scheduled to the edge nodes that are closest to users. If triggering rules are hit, edge
functions are triggered to process the requests and return results to the client. This helps significantly reduce the client
access latency.
Elastic Scaling
Edge Functions schedules requests to edge nodes that are allocated sufficient computing resources based on theproximity of the user when spikes occur in client requests.
Serverless Architecture
The serverless architecture of Edge Functions eliminates the need to focus on the maintenance of the memory, CPU,and network of servers and other infrastructure resources. You can focus on the development of business code.

Use Cases©2013-2022 Tencent Cloud. All rights reserved.

Page 7 of 360

Tencent Cloud EdgeOne

Use Limits
Content

Limit

Note

Number of Functions per Site

100 functions

A single site supports up to 100 edge functions.

Number of Trigger Rules per Site

200 rules

A single site supports up to 200 trigger rules forfunctions.

Function Name Length

30 characters

2 to 30 characters, up to 30 characters.

Code Package Size

5 MB

The maximum size for a single function code
package is 5 MB.

Request Body Size

1 MB

Client requests can carry a body up to 1 MB.

CPU Time

200 msCPU time slice allocated for single function
execution, excluding I/O waiting time.

©2013-2022 Tencent Cloud. All rights reserved.

Page 8 of 360

Tencent Cloud EdgeOne

Programming Language

Number of Console Invocations

JavaScript

Currently only JavaScript is supported.

20 times

Each function is allowed to call the console method
up to 20 times. Beyond 20 times, print operations
will no longer be executed.
In the function, the for , for in , for of ,Number of Loop Executions

100,000 times

while , do while loops are limited to
execute no more than 100,000 times.

©2013-2022 Tencent Cloud. All rights reserved.

Page 9 of 360

Tencent Cloud EdgeOne

Getting Started：

Last updated 2024-01-02 10:34:59
This document describes how to create a simple edge function and use the function to redirect a request to another
URL and return the custom response header.

Overview
The site example.com is currently connected to EdgeOne service. Under this site, a custom HTML activity pageneeds to be provided to the users through the custom domain name www.example.com . This page can be
deployed to the edge nodes of EdgeOne's global AZs through the edge function for users to access nearby.
Note:
1. How to connect to the site, please refer to Quick Start.
2. How to add an acceleration domain, please refer to Adding a Domain Name for Acceleration.

Directions
Step 1: Creating and Deploying a Function
1. Log in to the EdgeOne Console and click Site List in the left sidebar. In the site list, click the Site to be configured.
2. On the site details page, click Edge Function > Function Management.
3. On the edge function management page, click Create function and select to create a function using a template. At
this step, you can use a template to create a function according to actual business needs. Taking the current scenario
as an example, you can select the "Create Hello World" template to create a new one. After selecting the template,click Next.
4. On the new Edge Functions page, configure the relevant parameters. The explanations for these parameters are as
follows:
Function: Required, it can only contain letters, numbers, hyphens. It should start with a letter and end with a number or
letter, 2-30 characters; and it cannot be modified after creation. For example: test-edgefunctions.
Description: Optional, it supports up to 60 characters. For Example: Custom HTML page and response header.
Code: The edge function code that needs to respond. In the current scenario, you may copy the following function
code, paste it into the code editor of the console, and replace the default code in the editor.

©2013-2022 Tencent Cloud. All rights reserved.

Page 10 of 360

Tencent Cloud EdgeOne

const html = `<!DOCTYPE html><body><h1>Hello World</h1><p>This markup was generated by TencentCloud Edge Functions.</p><a href="https://cloud.tencent.com/product/teo">TencentCloud EdgeOne</a></body>`;async function handleRequest(request) {return new Response(html, {©2013-2022 Tencent Cloud. All rights reserved.

Page 11 of 360

Tencent Cloud EdgeOne

headers: {'content-type': 'text/html; charset=UTF-8','x-edgefunctions-test': 'Welcome to use Edge Functions.',},});}
addEventListener('fetch', event => {event.respondWith(handleRequest(event.request));});Note
The preceding code creates a custom HTML and adds the following custom response header: x-edgefunctions-test:
Welcome to use Edge Functions.
5. Click Create and deploy. If you see the following pop-up dialog box, the deployment is successful.

Step 2. Configuring a Triggering Rule
If you want to trigger function execution by setting HOST, URL Path, or file extensions of the matching sites, you could
proceed in the following two steps:
1. After the function is deployed successfully, click Add triggering rule.
2. On the add triggering rule page, configure the matching conditions. Taking the current scenario as an example, you
can select the Matching type as "HOST", the Operator as "Is", and the value as the added subdomainwww.example.com . Click OK to create the trigger rule.

©2013-2022 Tencent Cloud. All rights reserved.

Page 12 of 360

Tencent Cloud EdgeOne

Step 3: Verifying the Edge Function
To check whether the function is working as expected, you can initiate a request in a browser or by using Curl.
Browser Verification
Curl Verification
Enter the URL in the browser, for instance: https://www.example.com/test-edgefunctions . This URL
can match the set trigger conditions to trigger the execution of the function and view the response page information.

Run the curl request command within the MAC/Linux terminal to verify. For example: curl
https://www.example.com/test-edgefunctions . The response can be viewed as follows:©2013-2022 Tencent Cloud. All rights reserved.

Page 13 of 360

Tencent Cloud EdgeOne©2013-2022 Tencent Cloud. All rights reserved.

Page 14 of 360

Tencent Cloud EdgeOne

Operation Guide
Function Management：

Last updated 2024-01-02 10:24:04

Overview
This document describes how to create, edit, and delete an edge function, and how to configure the rules that trigger
the function.

Creating and Deploying a Function
1. Log in to the EdgeOne console, click Site List in the left sidebar, and click the site to be configured in the site list.
2. On the site details page, click on Edge Functions > Function Management.
3. On the Edge Function Management page, click Create function, select to create a function using a template. In
this step, you can create a function using a template on your actual business needs.
4. On the create new Edge Function page, configure the relevant parameters as follows:
Function: required, it can only include letters, numbers, hyphens. It must start with a letter and end with a digit or letter,
2-30 characters; it cannot be modified after creation. Example: test-edgefunctions.
Description: optional, it supports up to 60 characters. For instance, custom HTML page and response headers.
Code: the content of the edge function that requires a response.

©2013-2022 Tencent Cloud. All rights reserved.

Page 15 of 360

Tencent Cloud EdgeOne

5. Click on Create and deploy. If a dialog box appears as shown, it signifies the successful deployment.

After the deployment is successful, you can click Default access domain name assigned by the platform to verify its
effectiveness by triggering the function execution.

©2013-2022 Tencent Cloud. All rights reserved.

Page 16 of 360

Tencent Cloud EdgeOne

If the default function code is deployed, it will be displayed as follows:

Configuring a Triggering Rule
If you want to trigger function execution by setting HOST, URL Path or file suffix of the matching site, there are two
steps you can follow:
1. After the function is deployed successfully, click Add triggering rule.
2. On the Add triggering rule page, specify the matching type, operator, and value as needed.

©2013-2022 Tencent Cloud. All rights reserved.

Page 17 of 360

Tencent Cloud EdgeOne

3. Click OK.

Editing the Function
1. On the function management page, select the function you want to modify and click on Function.

©2013-2022 Tencent Cloud. All rights reserved.

Page 18 of 360

Tencent Cloud EdgeOne

2. On the function information page, click Save and deploy or Ctrl + S after modifying the function code.

3. Modify the code and click Save and deploy. If you have configured a triggering rule for the function, a note will be
displayed as follows:©2013-2022 Tencent Cloud. All rights reserved.

Page 19 of 360

Tencent Cloud EdgeOne

Deleting the Function
1. If you need to delete a newly created function, you can go to the function management page, select the function you
want to delete, and click on the Delete button in the operation column.

2. In the pop-up dialog box, click OK.
NoteOnce deleted, the function cannot be restored. The triggering rules of the function will also be deleted.

©2013-2022 Tencent Cloud. All rights reserved.

Page 20 of 360

Tencent Cloud EdgeOne

Function Trigger：

Last updated 2023-12-14 17:47:37

Scenarios
This document guides you how to manage function triggering rules.
Add, delete, modify and search for a triggering rule.
Adjust the priority of the triggering rules by reordering them in the list. If the request URL matches multiple triggeringrules, only the first hit rule is executed.

Directions
Creating a triggering rule
1. Log in to the EdgeOne console and click Site List in the left sidebar. In the site list, click the target site.
2. On the site details page, click Edge Functions > Function Management.
3. On the Function Trigger page, click theicon to the right of the rule list.

©2013-2022 Tencent Cloud. All rights reserved.

Page 21 of 360

Tencent Cloud EdgeOne

Parameter description:
Site: The name of the current site is displayed by default.
Description: (Optional) It can contain up to 60 characters.
Condition: Specify the matching type, operator, and value as needed. For more information, see Rule Engine.
Execute function: Select a function from the drop-down list.
4. Click OK to complete the creation.

Editing the triggering rule
1. On the Function Trigger page, find the rule and click Edit.

©2013-2022 Tencent Cloud. All rights reserved.

Page 22 of 360

Tencent Cloud EdgeOne

2. In the Edit triggering rule dialog box, modify the parameters and click OK.

©2013-2022 Tencent Cloud. All rights reserved.

Page 23 of 360

Tencent Cloud EdgeOne

Searching for the triggering ruleOn the Function Trigger page, click theicon to the right of the rule list and enter a keyword of the rule ID in the search box to search for the triggering rule.

©2013-2022 Tencent Cloud. All rights reserved.

Page 24 of 360

Tencent Cloud EdgeOne

Deleting the triggering rule
1. On the Function Trigger page, click theicon to the right of the rule list.
2. Find the rule to delete and click theicon.

3. In the pop-up dialog box, click Confirm to delete.

©2013-2022 Tencent Cloud. All rights reserved.

Page 25 of 360

Tencent Cloud EdgeOne

Adjusting the priority of the triggering rule
1. On the Function Trigger page, click theicon to the right of the rule list.
2. Find the rule. Click theicon to move the rule up by one row or theicon to move the rule down by one row. Then, click Save.
ReminderIf the request URL matches multiple triggering rules, such as Rules 01 and 02 in the following figure, only thetriggering rule on the top will be executed. In this example, only Rule 01 will be executed.

©2013-2022 Tencent Cloud. All rights reserved.

Page 26 of 360

Tencent Cloud EdgeOne

Use Cases
The following section describes how to adjust the execution order of multiple triggering rules that match the request
URL:
1. On the Function Management page, two functions with the same triggering rule are already created.

Code of the test1 function:©2013-2022 Tencent Cloud. All rights reserved.

Page 27 of 360

Tencent Cloud EdgeOne

const html = `<!DOCTYPE html><body><h1>The test 1, Hello World</h1><p>This markup was generated by a TencentCloud Edge Functions.</p><a href="https://cloud.tencent.com/product/teo">Tencent Cloud EdgeOne</a></body>`;async function handleRequest(request) {return new Response(html, {©2013-2022 Tencent Cloud. All rights reserved.

Page 28 of 360

Tencent Cloud EdgeOne

headers: {'content-type': 'text/html; charset=UTF-8','x-edgefunctions-test': 'Welcome to use Edge Functions.',},});}
addEventListener('fetch', event => {event.respondWith(handleRequest(event.request));});Code of the test2 function:©2013-2022 Tencent Cloud. All rights reserved.

Page 29 of 360

Tencent Cloud EdgeOne

const html = `<!DOCTYPE html><body><h1>The test 2, Hello World</h1><p>This markup was generated by a TencentCloud Edge Functions.</p><a href="https://cloud.tencent.com/product/teo">Tencent Cloud EdgeOne</a></body>`;async function handleRequest(request) {return new Response(html, {©2013-2022 Tencent Cloud. All rights reserved.

Page 30 of 360

Tencent Cloud EdgeOne

headers: {'content-type': 'text/html; charset=UTF-8','x-edgefunctions-test': 'Welcome to use Edge Functions.',},});}
addEventListener('fetch', event => {event.respondWith(handleRequest(event.request));});2. The triggering rules are displayed on the Function Trigger page, as shown in the following figure.

3. The triggering rule of the test1 function is listed in position 01, and that of the test2 function is in position
02, as shown in the following figure.

©2013-2022 Tencent Cloud. All rights reserved.

Page 31 of 360

Tencent Cloud EdgeOne

4. Enter the URL that contains the triggering rule in the address bar of a browser and press Enter. The following
results are returned.

5. Click theicon of the test2 function and then click Save.

6. The triggering rule of the test2 function is adjusted to position 01, and that of the test1 function is adjusted
to position 02.
7. Enter the URL that contains the triggering rule in the address bar of a browser and press Enter. The response is as
below:©2013-2022 Tencent Cloud. All rights reserved.

Page 32 of 360

Tencent Cloud EdgeOne©2013-2022 Tencent Cloud. All rights reserved.

Page 33 of 360

Tencent Cloud EdgeOne

Environment Variable：

Last updated 2024-08-05 16:49:47

Operation scenarios
Environment Variables are key-value pairs set in the running environment of Edge Functions, which can be accessed
as global variables in Edge Function scripts without the need for explicit importing or initialization. By using
Environment Variables, function code can be decoupled from configuration. Their common uses are as follows:
Configuration Decoupling: Environment Variables allow developers to configure Edge Functions without modifying thefunction's code, meaning developers can set different values for different environments (such as development, testing,and production) to control function behavior.
Security: By storing Sensitive Information (like API Keys) in Environment Variables instead of hardcoding them into
the code, application security is enhanced. This approach reduces the Risk of leakage of Sensitive Information in thecode repository and simplifies Key Management.
Flexibility: Environment Variables provide great Flexibility for Edge Functions, allowing developers to adjust the
behavior of Edge Functions as needed. For example, developers can use Environment Variables to achieve Gray
release, by controlling different User Groups to access different versions of code or configuration.

Operation Introduction
1. Log in into the TencentCloud EdgeOne console, click on Site List in the left sidebar. Subsequently, within the Site
List, select the site you wish to configure.
2. On the website details page, click on Edge Function > Function Management.
3. On the Function Management page, click Specific Function Name. At the bottom of the page, find theEnvironment Variables section. If the function has not been created, please follow the Create and Deploy Function
guide to complete the function creation first.

Create and Deploy Environment Variables
1. In the Environment Variables section, click Quick addition and configure the relevant parameters.

©2013-2022 Tencent Cloud. All rights reserved.

Page 34 of 360

Tencent Cloud EdgeOne

Parameter name

Variable name

Description
Required fields can only include uppercase and lowercase letters, numbers, andspecial characters limited to @,.,-,, . The length is restricted to 1 to 64
characters. The variable name cannot be duplicated and cannot be modified after
creation. For example: keytest.
Required fields support String and JSON types.
String: After selecting this option, the input variable value content will be saved as astring. For specific usage, please refer to the Edge Function References Environment
Variables section for the variable type String.

Variable type

JSON: After selecting this option, the input variable value content will be saved as a
JSON array. The Edge Function will automatically parse the variable value into a
JavaScript object without the need to manually call JSON.parse(). For specificusage, please refer to the Edge Function References Environment Variables section
for the variable type JSON.

Variable value

Required fields support a maximum of 5 KB. For example: if the type is String, enter
valuetest as the variable value. If the type is JSON, the variable value will bevalidated to check if the input content follows the JSON Data Structure. If it does not,there will be an Exception Prompt.

©2013-2022 Tencent Cloud. All rights reserved.

Page 35 of 360

Tencent Cloud EdgeOne

2. Click Confirm, to complete the creation of the environment variable. A single Edge Function supports creating up to
64 environment variables.

3. Click Deploy to make it effective.

Edge Functions introduce environment variables
If the environment variables referenced by the function do not contain special characters : @,.,-,,, , they can bereferenced in the form of env.envname. For example: if the environment variable envname is: keytest , the way toreference it in edge function code is env.keytest . For detailed usage, refer to the String type section.
If the environment variable name referenced by the function contains special characters : @,.,-,,, , they can bereferenced in the form of env['envname']. For example: if the environment variable envname is: test-@.-a , theway to reference it in edge function code is env['test-@.-a'] .
Below is sample code for edge functions referencing environment variables of types String and JSON. Developers
can adjust according to actual requirements.
Variable Type: String
Through the above steps to create and deploy environment variables, create an environment variable named
keytest with the value valuetest . The edge function reference is as follows:©2013-2022 Tencent Cloud. All rights reserved.

Page 36 of 360

Tencent Cloud EdgeOne// Entry function
addEventListener('fetch', event => {event.respondWith(handleRequest(event.request));});// Function to handle requests
async function handleRequest(request) {// Get value from environment variable, this environment variable needs to be cre
const valueFromEnv = env.keytest;// Create response
const response = new Response(valueFromEnv, {©2013-2022 Tencent Cloud. All rights reserved.

Page 37 of 360

Tencent Cloud EdgeOne

headers: {'Content-Type': 'text/plain' // Set the response Content-Type}});// Return the response
return response;}
The semantic summary of the above code is to get the environment variable that the function has created anddeployed, and respond it to the client as text.
Deploy the code, and you can view the result by accessing the trigger rules or default access of the function.

Variable type: JSON
Repeat the steps to create and deploy environment variables, and create and deploy an environment variable of type
JSON named keytestjson , as shown below:©2013-2022 Tencent Cloud. All rights reserved.

Page 38 of 360

Tencent Cloud EdgeOne// Entry function
addEventListener('fetch', event => {event.respondWith(handleRequest(event.request));});async function handleRequest(request) {// Get value from environment variable, this environment variable needs to be creat
const myJsonData = env.keytestjson;// Create Response Body
const response = new Response(JSON.stringify(myJsonData), {headers: {©2013-2022 Tencent Cloud. All rights reserved.

Page 39 of 360

Tencent Cloud EdgeOne'Content-Type': 'application/json'}});// Return the response
return response;}
The semantic summary of the above code is to get the environment variable that the function has created anddeployed, and respond it to the client as JSON data.
Deploy the code, and you can view the result by accessing the trigger rules or default access of the function.

Edit Environment Variable
1. In the Environment Variables module, click Edit for a specific environment variable. In the popup window, you canchange the variable type and variable value. Click Confirm to save the edited content.
2. In the Environment Variables module, click Deploy. The popup window will display the specific updates for thisoperation. Click Confirm to complete the deployment.

©2013-2022 Tencent Cloud. All rights reserved.

Page 40 of 360

Tencent Cloud EdgeOne

Delete Environment Variable
In the Environment Variables section, click Delete for a specific environment variable, then click Deploy. The popup
window will display the specific environment variables being deleted in this operation. Click Confirm to complete thedeployment.

Note:
If the environment variables referenced by the function are deleted through the above operations, please adjust thelogic of related references in the function code.

©2013-2022 Tencent Cloud. All rights reserved.

Page 41 of 360

Tencent Cloud EdgeOne

Runtime APIs
addEventListener：

Last updated 2023-03-08 11:26:27
This API is used to register an event listener for a target. The event listener triggers an edge function when thespecified type of event is delivered to the target. Only one event listener takes effect for the same type of event. Only
fetch request events are supported currently. If a fetch event occurs after a fetch event listener isregistered, the event listener generates a FetchEvent object to process the HTTP request.

Overview©2013-2022 Tencent Cloud. All rights reserved.

Page 42 of 360

Tencent Cloud EdgeOne

function addEventListener(type: string, listener: (event: FetchEvent) => void): voi

Parameters
Parameter

Type

Required

Description

type

stringYes

Event type.
Only fetch request events are supported.
If you specify a request event type other thanfetch , the Edge Functions engine throws an©2013-2022 Tencent Cloud. All rights reserved.

Page 43 of 360

Tencent Cloud EdgeOne

Error exception.

listener(event: FetchEvent) => void

Yes

Event listener that is used to process event
callbacks.
You can register a fetch event listener togenerate FetchEvent objects.

Sample Code©2013-2022 Tencent Cloud. All rights reserved.

Page 44 of 360

Tencent Cloud EdgeOne// Register a fetch event listener.
addEventListener('fetch', (event) => {// Respond to the client.
event.respondWith(new Response('Hello World!'));});

References
MDN documentation: addEventListenerSample Functions: Returning an HTML Page
Sample Functions: Returning a JSON Object©2013-2022 Tencent Cloud. All rights reserved.

Page 45 of 360

Tencent Cloud EdgeOne

Cache
：

Last updated 2024-01-31 10:10:01
The Cache API is designed based on the standard Web API Cache. During the runtime of edge functions, a global
caches object that provides a group of methods for cache-related operations is injected.
Note:
The cached content takes effect only on the current data node and is not automatically copied to other data nodes.

Constructor API
Use caches.default to fetch the default cache instance.

©2013-2022 Tencent Cloud. All rights reserved.

Page 46 of 360

Tencent Cloud EdgeOne// Fetch the default cache instance.
const cache = caches.default;// This method provides the same effect as `caches.default`.
await caches.open('default');
Use caches.open to create a cache instance with the specified namespace.

©2013-2022 Tencent Cloud. All rights reserved.

Page 47 of 360

Tencent Cloud EdgeOne// Create a cache instance with the specified namespace.
const cache = await caches.open(namespace);

Parameters
The following table describes the parameters of the caches.open(namespace) method.
Parameter

Type

Required

Description

namespacestringYes

The namespace of the cache.

©2013-2022 Tencent Cloud. All rights reserved.

Page 48 of 360

Tencent Cloud EdgeOne

The value "default" specifies the default instance. You
can also use caches.default to fetch a default instance.

Methods
match

cache.match(request: string | Request, options?: MatchOptions): Promise<Response |©2013-2022 Tencent Cloud. All rights reserved.

Page 49 of 360

Tencent Cloud EdgeOne

The match() method fetches the Response cache associated with the request and returns a Promise object. If thecache exists, the object contains the Response object. If not, the object contains undefined.
Note:
The cache.match() method does not forward requests to the origin. If the cache expires, the method throws a 504
error.
Parameters
Parameter

Type

Required

Description
The request object. The following method and headers aresupported:
GET
Only the GET method is supported. If this parameter is set to astring, the string is used as a URL to construct a Request object.
Range
If the request contains a Range header and the cachedresponse contains the Accept-Ranges header, the 206
response is returned.
If-Modified-Since
If the request contains a If-Modified-Since header and thecached response contains a Last-Modified header with thesame value as that of the If-Modified-Since header, the 304
response is returned.
If-None-Match
If the request contains a If-None-Match header and the cachedresponse contains an ETag header with the same value as thatof the If-Modified-Since header, the 304 response is returned.

requeststring |RequestYes

options

MatchOptions

No

Type

ExampleDescription

trueSpecifies whether to ignore the request method. If you set thisparameter to true, the request is considered to be a GET request
regardless of its actual method.

The options.

MatchOptions
Parameter

ignoreMethod

booleanput©2013-2022 Tencent Cloud. All rights reserved.

Page 50 of 360

Tencent Cloud EdgeOne

cache.put(request: string | Request, response: Response): Promise<undefined>
The put() method tries to add a response to the cache by using the given request as the cache key. A
Promise<undefined> object is returned regardless of whether caching is successful.
Note:
The put() method returns a 413 error if the Cache-Control header of the object specified in the response parameter
instructs not to cache.
Parameters©2013-2022 Tencent Cloud. All rights reserved.

Page 51 of 360

Tencent Cloud EdgeOne

Parameter

requestType

string |RequestRequired

Description
The cache key.
GET
The request

Yes

parameter supports only the GET method. Ifother methods are specified, an error is thrown.
stringIf the request parameter is set to a string, the string isused as a URL to construct a Request object.
The cache content.
Cache-Control
Valid values: s-maxage, max-age, no-store, no-cache, andprivate. The values no-store, no-cache, and private indicate nocaching. If you use these values, the cache.put method
returns a 413 error.

response

Response

Yes

PragmaIf Cache-Control is not specified and Pragma is set to nocache, no caching is performed.
ETag
If the request parameter of the cache.match method
contains a If-None-Match header, you can associate it withETag.
Last-Modified
if the request parameter of the cache.match method
contains a If-Modified-Since header, you can associate it with
Last-Modified.
416 Range Not Satisfiable
If the object specified in the response parameter is 416
Range Not Satisfiable, no caching is performed.

Parameter limits
The cache.put method throws an error in the following scenarios:
The request parameter specifies a method other than the GET method.
The status code of the response parameter is 206 Partial Content.
The response parameter contains a Vary: * header.

delete©2013-2022 Tencent Cloud. All rights reserved.

Page 52 of 360

Tencent Cloud EdgeOne

cache.delete(request: string | Request, options?: DeleteOptions): Promise<boolean>
The delete() method deletes the response associated with the request from the cache. If no network exception occurs,a Promise containing true is returned. Otherwise, a Promise containing false is returned.
Parameters
Parameter

Type

Required

Description

requeststring |RequestYes

The cache key.
GET

©2013-2022 Tencent Cloud. All rights reserved.

Page 53 of 360

Tencent Cloud EdgeOne

The request parameter supports only the GET method.
stringIf the request parameter is set to a string, the string isused as a URL to construct a Request object.
options

DeleteOptions

No

The options.

DeleteOptions
Parameter

ignoreMethodTypeboolean

ExampleDescription

trueSpecifies whether to ignore the request method. If you set thisparameter to true, the request is considered to be a GET request
regardless of its actual method.﻿

References
MDN documentation: Cache﻿Sample Functions: Caching POST Requests
Sample Functions: Using the Cache API©2013-2022 Tencent Cloud. All rights reserved.

Page 54 of 360

Tencent Cloud EdgeOne

Cookies：

Last updated 2024-01-30 17:12:01
The Cookies API provides a group of methods for you to manage cookies.
Note:
The unique keys of Cookies objects are in the format of name + domain + path . You can manage Cookies
objects based on the unique keys.

Constructor API©2013-2022 Tencent Cloud. All rights reserved.

Page 55 of 360

Tencent Cloud EdgeOne

const cookies = new Cookies(cookieStr?: string, isSetCookie?: boolean);Parameters
Parameter

Type

Required

Description

cookieStr

stringNo

The Cookie string or Set-Cookie string.

isSetCookie

booleanNo

Specifies whether the value of the cookieStr parameter is a SetCookie string. Default value: false.

©2013-2022 Tencent Cloud. All rights reserved.

Page 56 of 360

Tencent Cloud EdgeOne

Methods
getcookies.get(name?: string): null | Cookie | Array<Cookie>;
The get() method obtains the Cookie object of the specified name. If multiple objects are matched, a Cookie array isreturned.
Parameters©2013-2022 Tencent Cloud. All rights reserved.

Page 57 of 360

Tencent Cloud EdgeOne

Parameter

name

Type

stringRequired

Description

No

The name of Cookie object. Valid options:Default name
Obtains all Cookie objects.
Specified name
Obtains the Cookie object of the specified name. If multiple objects arematched, a Cookie array is returned.

Cookie
The following table describes the attributes of the Cookie object. For more information, see Set-Cookie.
Attribute

Type

Readonly

Description

namestringYes

The name of the Cookie object.

valuestringYes

The value of the Cookie object.

domainstringYes

The host to which the Cookie object will be sent.

path

stringYes

The path to which the Cookie object will be sent.

expiresstringYes

The maximum effective time of the Cookie object. The value meets the
HTTP Date header standards.

max_agestringYes

The number of seconds until the Cookie object expires.

samesite

stringYes

Controls whether the Cookie object is sent with cross-site requests,
providing some protection against cross-site request forgery (CSRF)
attacks.

httponlyboolean

Yes

Forbids JavaScript from accessing the Cookie object. The attribute iscarried only by HTTP requests.

securebooleanYesSpecifies that the Cookie object can be carried only by HTTPS requests.

set©2013-2022 Tencent Cloud. All rights reserved.

Page 58 of 360

Tencent Cloud EdgeOne

cookies.set(name: string, value: string, options?: Cookie): boolean;
The set() method adds cookies in overwrite mode. If true is returned, cookies are successfully added. If false
is returned, cookies fail to be added because the number of cookies exceeds the upper limit. For more information,
see Cookie limits.
Note:
Cookies are added in overwrite mode based on unique keys in the format of name + domain + path .
Parameters©2013-2022 Tencent Cloud. All rights reserved.

Page 59 of 360

Tencent Cloud EdgeOne

Parameter

Type

Required

Description

namestringYes

The name of the Cookie object.

valuestringYes

The value of the Cookie object.

Cookiestring

No

The configuration items of the Cookie object.

appendcookies.append(name: string, value: string, options?: Cookie): boolean;©2013-2022 Tencent Cloud. All rights reserved.

Page 60 of 360

Tencent Cloud EdgeOne

The append() method appends cookies in scenarios where multiple values correspond to the same name. If true
is returned, cookies are successfully appended. If false is returned, cookies fail to be appended because thevalue already exists or the number of cookies exceeds the upper limit. For more information, see Cookie limits.
Note:
Cookies are appended based on unique keys in the format of name + domain + path .

removecookies.remove(name: string, options?: Cookie): boolean;©2013-2022 Tencent Cloud. All rights reserved.

Page 61 of 360

Tencent Cloud EdgeOne

The remove() method deletes cookies.
Note:
Cookies are deleted based on unique keys in the format of name + domain + path .
Parameters
Parameter

Type

Required

Description

namestringYes

The name of the Cookie object.

options

CookieYes

The configuration items of the Cookie object. The configuration items`domain` and `path` support the wildcard character (*), indicating that allitems are matched.

Use Limits
Automatic escape of special characters
The following characters are automatically escaped if they are contained in the value of the name attribute:" () , / : ; ? < = > ? @ [ ] \\ { } . 0x00~0x1F and 0x7F~0xFF .
The following characters are automatically escaped if they are contained in the value of the value attribute:， ; " \\ . 0x00~0x1F and 0x7F~0xFF .

,Cookie limits
The size of the Cookie attribute name cannot exceed 64 bytes.
The accumulated size of the Cookie attributes value, domain, path, expires, max_age, andsamesite cannot exceed 1 KB.
The total length of all fields after escape of cookies cannot exceed 4 KB.
The total number of Cookie objects contained in cookies cannot exceed 64.

Sample Code©2013-2022 Tencent Cloud. All rights reserved.

Page 62 of 360

Tencent Cloud EdgeOne

function handleEvent(event) {const response = new Response('hello world');// Generate a Cookies object.
const cookies = new Cookies('ssid=helloworld; expires=Sun, 10-Dec-2023 03:10:01 G// Set the response header Set-Cookie.
response.setCookies(cookies);
return response;}©2013-2022 Tencent Cloud. All rights reserved.

Page 63 of 360

Tencent Cloud EdgeOne

addEventListener('fetch', (event) => {event.respondWith(handleEvent(event));});

References
MDN documentation: Set-Cookie
Sample Functions: Performing an A/B Test
Sample Functions: Setting Cookies©2013-2022 Tencent Cloud. All rights reserved.

Page 64 of 360

Tencent Cloud EdgeOne

Encoding：

Last updated 2024-01-30 16:56:26
The encoder and decoder are designed based on standard Web APIs TextEncoder and TextDecoder.

TextEncoder
The TextEncoder API takes code point streams as inputs and generates UTF-8 byte streams as outputs. For more
information, see TextEncoder.

Constructor API©2013-2022 Tencent Cloud. All rights reserved.

Page 65 of 360

Tencent Cloud EdgeOne// The TextEncoder() constructor does not have any parameters.
const encoder = new TextEncoder();

Attributes©2013-2022 Tencent Cloud. All rights reserved.

Page 66 of 360

Tencent Cloud EdgeOne// encoder.encoding
readonly encoding: string;
The name of the encoding algorithm that is used by the encoder. The value is fixed to UTF-8 .

Methods
encode©2013-2022 Tencent Cloud. All rights reserved.

Page 67 of 360

Tencent Cloud EdgeOne

encoder.encode(input?: string | undefined): Uint8Array
The encoder.encode() method takes code point streams as inputs and generates UTF-8 byte streams as outputs.
Note:
The maximum length of input is 300 MB. An exception will be thrown if the maximum length is exceeded.
encoder.encode parameters
Parameter

Type

Required

Description

input

string | undefinedNo

The text to be encoded.

©2013-2022 Tencent Cloud. All rights reserved.

Page 68 of 360

Tencent Cloud EdgeOne

encodeInto

encoder.encodeInto(input: string, destination: Uint8Array): EncodeIntoResult;
The encoder.encodeInto() method takes code point streams as inputs, generates UTF-8 byte streams as outputs,
and writes the outputs to a destination byte array.
Parameters
Parameter

Type

Required

Description

input

stringYes

The text to be encoded.

©2013-2022 Tencent Cloud. All rights reserved.

Page 69 of 360

Tencent Cloud EdgeOne

destination

Uint8ArrayYes

The object in which the encoded text is stored.

Return value: EncodeIntoResult
Parameter

Type

Description

read

number

The number of UTF-16 units that have been converted to UTF-8.

writtennumber

The number of bytes that are modified in the destination Uint8Array.

TextDecoder
The TextDecoder API takes byte streams as inputs and generates code point streams as outputs. For more
information, see TextDecoder.

Construction API©2013-2022 Tencent Cloud. All rights reserved.

Page 70 of 360

Tencent Cloud EdgeOne

const decoder = new TextDecoder(label?: string | undefined, options?: DecoderOption

Parameters
Note:
The label parameter does not support the following values:
iso-8859-16
hz-gb-2312
csiso2022kr, iso-2022-kr©2013-2022 Tencent Cloud. All rights reserved.

Page 71 of 360

Tencent Cloud EdgeOne

Parameter

Type

Required

Descriptionlabel

string |undefinedNo

The name of the decoding algorithm that is used by the
decoder. Default value: UTF-8. For the valid values of label,see Encoding API Encodings.

options

DecoderOptions| undefinedNo

The configuration items of the decoder.

DecoderOptions
The following table describes the configuration items of the decoder.
Parameter

Type

Default value

Description

fatalbooleanfalse

Specifies whether to throw an exception when decoding fails.

ignoreBOM

booleanfalse

Specifies whether to ignore byte-order marker.

Attributes
encoding©2013-2022 Tencent Cloud. All rights reserved.

Page 72 of 360

Tencent Cloud EdgeOne// decoder.encoding
readonly encoding: string;
The name of the decoding algorithm that is used by the decoder.
fatal©2013-2022 Tencent Cloud. All rights reserved.

Page 73 of 360

Tencent Cloud EdgeOne// decoder.fatal
readonly fatal: boolean;Specifies whether to throw an exception when decoding fails.
ignoreBOM©2013-2022 Tencent Cloud. All rights reserved.

Page 74 of 360

Tencent Cloud EdgeOne// decoder.ignoreBOM
readonly ignoreBOM: boolean;Specifies whether to ignore byte-order marker.

Methods
decode©2013-2022 Tencent Cloud. All rights reserved.

Page 75 of 360

Tencent Cloud EdgeOne

const result = decoder.decode(buffer?: ArrayBuffer | ArrayBufferView | undefined, oNote:
The maximum length of buffer is 100 MB. An exception will be thrown if the maximum length is exceeded.
ParameterTypebufferArrayBuffer |ArrayBufferView| undefined

Required

Description

No

The byte stream to be decoded.
The maximum length of buffer is 100 MB. An exception willbe thrown if the maximum length is exceeded.

©2013-2022 Tencent Cloud. All rights reserved.

Page 76 of 360

Tencent Cloud EdgeOne

options

DecodeOptions

No

The configuration items for decoding.

DecodeOptions
The following table describes the configuration items for decoding.
Parameter

streamTypebooleanDefault
value

false

Description
Specifies whether to perform decoding in streaming mode.
Default value: false. Valid values:
true
Perform decoding in streaming mode. Use this value if data isprocessed in chunks and additional chunks are expected.
false
Do not perform decoding in streaming mode. Use this value if
the current chunk is the last one or data is not chunked.

Sample Code©2013-2022 Tencent Cloud. All rights reserved.

Page 77 of 360

Tencent Cloud EdgeOne

function handleEvent(event) {// Encoder
const encoder = new TextEncoder();
const encodeText = encoder.encode('hello world');// Decoder
const decoder = new TextDecoder();
const decodeText = decoder.decode(encodeText);// Response
const response = new Response(JSON.stringify({©2013-2022 Tencent Cloud. All rights reserved.

Page 78 of 360

Tencent Cloud EdgeOne

encodeText: encodeText.toString(),
decodeText,}));
return response;}
addEventListener('fetch', (event) => {event.respondWith(handleEvent(event));});

References
MDN documentation: TextEncoder
MDN documentation:TextDecoder
MDN documentation: Encoding API Encodings
Sample Functions: Protecting Data from Tampering©2013-2022 Tencent Cloud. All rights reserved.

Page 79 of 360

Tencent Cloud EdgeOne

Fetch
：

Last updated 2023-09-12 09:55:42
The Fetch API is designed based on the standard Web API Fetch. You can add fetch to the edge function
runtime to initiate an async request to fetch remote.

Description©2013-2022 Tencent Cloud. All rights reserved.

Page 80 of 360

Tencent Cloud EdgeOne

function fetch(request: string | Request, requestInit?: RequestInit): Promise<Respo

Parameters
Parameter
namerequestType
string |RequestRequired

Description

Yes

Requested resource.

©2013-2022 Tencent Cloud. All rights reserved.

Page 81 of 360

Tencent Cloud EdgeOne

requestInit

RequestInit

No

Initial configuration items of the request object. For more
information, see RequestInit.

Advanced Features
With fetch , you can pass in specific parameters for finer configuration of EdgeOne node caching, fetching fromthe origin, image processing and redirection.

Accessing EdgeOne nodes or fetching from the origin
When a client request comes to a domain name domain name connected to EdgeOne (such as www.example.com), if
the request triggers an edge function, fetch(www.example.com) is executed in the edge function. The request
is directed to the cache on the EdgeOne node. If no cache is hit, the request is redirected to the origin.
Restrictions and requirements:
1. The domain name is connected to EdgeOne and the request triggers the edge function.
2. HOST of request.url specified in fetch(request) is the same as the HOST of client request URL.
3. HOST of request.headers.host specified in fetch(request) is the same as the HOST of client
request URL.
Use fetch(event.request) to obtain the cache from EdgeOne nodes and pull resources from the origin if nocache is hit.

©2013-2022 Tencent Cloud. All rights reserved.

Page 82 of 360

Tencent Cloud EdgeOne

addEventListener('fetch', (event) => {//Use `fetch(event.request)` to obtain the cache from EdgeOne nodes and pull reso
const response = fetch(event.request);
event.respondWith(response);});
Use fetch(url) to obtain the cache from EdgeOne nodes and pull resources from the origin if no cache is hit.

©2013-2022 Tencent Cloud. All rights reserved.

Page 83 of 360

Tencent Cloud EdgeOne

addEventListener('fetch', (event) => {event.respondWith(handleEvent(event));});
async function handleEvent(event) {const { request } = event;const urlInfo = new URL(request.url);// origin-pull URL rewrite
const url = `${urlInfo.origin}/h5/${urlInfo.pathname}`;// fetch(url) collected EdgeOne CDN Cache and origin-pull.

©2013-2022 Tencent Cloud. All rights reserved.

Page 84 of 360

Tencent Cloud EdgeOne

const response = await fetch(url);
return response;}

Image processing
You can use requestInit.eo.image to scale images or convert the image format. For details, see
ImageProperties.
Note:
To use fetch(request, requestInit) to process images, the requirements for using fetch to obtaincache and pull from the origin must be met.

Redirection
fetch supports 3xx redirect status codes. You can use the second parameter requestInit.redirectto specify the redirect status code. For more information, see RequestInit.
Redirect rules conform to the Fetch Standard. The follow rules vary based on the status code.
Status code

Redirect Rule

301 and 302

Replaces the POST method with the GET method.

303

Replaces all request methods except for HEAD and GET with the GET method.

307 and 308

Retains the original request method.

Important
The redirect address is obtained from the Location response header. If Location does not exist, no redirect
action is taken.
The value of the Location can be an absolute URL or a relative URL. For more information, see RFC-3986: URI
Reference.

Runtime limits
If you use fetch to initiate a request in an edge function, take note of the following limits:
Number of times: Each time an edge function runs, fetch can be initiated for a maximum of 64 times. If the limit isexceeded, the exceeding requests fail and exceptions are returned.
Number of concurrencies: Each time an edge function runs, fetch can be initiated at a maximum concurrency of
8. If the limit is exceeded, the exceeding requests are postponed until a running fetch is resolved.
Note
Each redirect is counted as a request and has a higher priority than newly-initiated fetch requests.

©2013-2022 Tencent Cloud. All rights reserved.

Page 85 of 360

Tencent Cloud EdgeOne

References
MDN documentation: Fetch
Sample functions: Obtaining Remote Resources and Responding to the Client©2013-2022 Tencent Cloud. All rights reserved.

Page 86 of 360

Tencent Cloud EdgeOne

FetchEvent：

Last updated 2024-01-30 16:48:21
A FetchEvent object represents any incoming HTTP request event. Edge Functions processes HTTP requests byregistering fetch event listeners.

Overview
In Edge Functions, use addEventListener to register a fetch event listener to generate an HTTP request event
FetchEvent, thereby processing HTTP requests.
Note:
The FetchEvent object cannot be constructed directly. You can use addEventListener to register afetch event listener to obtain the event object.

©2013-2022 Tencent Cloud. All rights reserved.

Page 87 of 360

Tencent Cloud EdgeOne// `event` is the `FetchEvent` object.
addEventListener('fetch', (event) => {event.respondWith(new Response('hello world!'));});

Attributes
ClientId©2013-2022 Tencent Cloud. All rights reserved.

Page 88 of 360

Tencent Cloud EdgeOne// event.clientId
readonly clientId: string;
The ClientId attribute specifies the ID allocated by Edge Functions for each request.

request©2013-2022 Tencent Cloud. All rights reserved.

Page 89 of 360

Tencent Cloud EdgeOne// event.request
readonly request: Request;
The request attribute specifies the HTTP request object initiated by the client. For more information, see Request.

Methods
respondWith©2013-2022 Tencent Cloud. All rights reserved.

Page 90 of 360

Tencent Cloud EdgeOne

event.respondWith(response: Response | Promise<Response>): void;
Edge Functions takes over requests from the client and uses this method to return custom responses.
Note:
In the fetch event callback of the addEventListener event listener, the event.respondWith()
method is used to respond to the client. If this method is not invoked, Edge Functions forwards the current request
back to the origin.
Parameters©2013-2022 Tencent Cloud. All rights reserved.

Page 91 of 360

Tencent Cloud EdgeOne

Parameter
response

Type
Response
Promise<Response>

RequiredYes

Description
The response to the HTTP request of theclient.

waitUntil

event.waitUntil(task: Promise<any>): void;©2013-2022 Tencent Cloud. All rights reserved.

Page 92 of 360

Tencent Cloud EdgeOne

The waitUntil() method is used to notify Edge Functions to wait until a Promise -based task is completed,
extending the event processing lifecycle.
Parameters
Parameter

Type

Requiredtask

Promise<Response>

Yes

Description
The `Promise`-based task.

passThroughOnException©2013-2022 Tencent Cloud. All rights reserved.

Page 93 of 360

Tencent Cloud EdgeOne

event.passThroughOnException(): void;
The passThroughOnException() method is used to prevent runtime error responses. If the function code throws anunhandled exception, Edge Functions forwards the request back to the origin, enhancing the service availability.

Sample CodeIf the event.respondWith method is not invoked, Edge Functions forwards the current request back to theorigin.

©2013-2022 Tencent Cloud. All rights reserved.

Page 94 of 360

Tencent Cloud EdgeOne

function handleRequest(request) {return new Response('Edge Functions, Hello World!');}addEventListener('fetch', event => {const request = event.request;// If the request URL contains the string /ignore/, Edge Functions forwards the cif (request.url.indexOf('/ignore/') !== -1) {// The event.respondWith method is not invoked.
return;}// Customize content in the edge function to respond to the client.
event.respondWith(handleRequest(request));});If the function code throws an unhandled exception, Edge Functions forwards the current request back to the origin.

©2013-2022 Tencent Cloud. All rights reserved.

Page 95 of 360

Tencent Cloud EdgeOne

addEventListener('fetch', event => {// If the function code throws an unhandled exception, Edge Functions forwards thevent.passThroughOnException();throw new Error('Throw error');});

References©2013-2022 Tencent Cloud. All rights reserved.

Page 96 of 360

Tencent Cloud EdgeOne

MDN documentation: FetchEvent
Sample Functions: Returning an HTML Page
Sample Functions: Using the Cache API©2013-2022 Tencent Cloud. All rights reserved.

Page 97 of 360

Tencent Cloud EdgeOne

Headers：

Last updated 2023-09-12 09:50:38
The Headers API is designed based on the standard Web API Headers. You can use this API to perform operations
on HTTP request and response headers.

Constructor API©2013-2022 Tencent Cloud. All rights reserved.

Page 98 of 360

Tencent Cloud EdgeOne

const headers = new Headers(init?: object | Array<[string, string]> | Headers);

Parameters
Parameter

Type

Requiredinit

object |No

Array<[string,

Description
The HTTP header that is used to pre-populate the
Headers object. Valid parameter types:

string]> |Headers©2013-2022 Tencent Cloud. All rights reserved.

Page 99 of 360

Tencent Cloud EdgeOne

object

The Constructor API enumerates all enumerable
attributes that are included in the specified object and prepopulates the attributes to the new Headers object.

Array<[string, string]>

Each element in the array is a key-value pair. Example:[key, value]. The Constructor API traverses the array and prepopulates the key-value pairs to the new Headers object.

Headers

The Constructor API copies all fields from an existing
Headers object to the new Headers object.

Methods
append©2013-2022 Tencent Cloud. All rights reserved.

Page 100 of 360

Tencent Cloud EdgeOne

headers.append(name: string, value: string): void;
The append() method appends a new value to a header that is specified by the Headers object. If the header does
not exist, the append() method directly adds the header.
Parameters
Parameter

Type

Required

Description

namestringYes

The name of the HTTP header that you want to add to the Headers object.

©2013-2022 Tencent Cloud. All rights reserved.

Page 101 of 360

Tencent Cloud EdgeOne

value

stringYes

The value of the HTTP header that you want to add.

deleteheaders.delete(name: string): void;
The delete() method deletes the specified header from the Headers object.

©2013-2022 Tencent Cloud. All rights reserved.

Page 102 of 360

Tencent Cloud EdgeOne

Parameters
Parameter

Type

Required

Description

namestringYes

The name of the HTTP header that you want to delete from the Headers
object.

entries©2013-2022 Tencent Cloud. All rights reserved.

Page 103 of 360

Tencent Cloud EdgeOne

headers.entries(): iterator;
The entries() method obtains an array of all key-value pairs from the Headers object. The key-value pairs are in
the format of [name, value]. For valid return values, see Iteration protocols.

forEachheaders.forEach(callback: (name: string, value: string) => void | number): void;
The forEach() method traverses all headers that are included in the Headers object. If callback returns a
non-zero value, traversal is stopped.

©2013-2022 Tencent Cloud. All rights reserved.

Page 104 of 360

Tencent Cloud EdgeOne

Note
The forEach method does not comply with Web API standards. Edge Functions extends the functionality of themethod based on Web API standards to provide an efficient way to traverse headers.

getheaders.get(name: string): string;
The get() method obtains the value of the specified header from the Headers object.

©2013-2022 Tencent Cloud. All rights reserved.

Page 105 of 360

Tencent Cloud EdgeOne

getSetCookie

headers.getSetCookie(): Array<string>This method returns an array, containing all values of the Set-Cookie headers.

has©2013-2022 Tencent Cloud. All rights reserved.

Page 106 of 360

Tencent Cloud EdgeOne

headers.has(name: string): boolean;
The has() method checks whether the Headers object contains the specified header.

keys©2013-2022 Tencent Cloud. All rights reserved.

Page 107 of 360

Tencent Cloud EdgeOne

headers.keys(): iterator;
The keys() method obtains all keys that are included in the Headers object. For valid return values, see Iteration
protocols.

set©2013-2022 Tencent Cloud. All rights reserved.

Page 108 of 360

Tencent Cloud EdgeOne

headers.set(name: string, value: string): void;
The set() method sets a new value for an existing header in the Headers object. If the header does not exist, theset() method directly adds the header.

values©2013-2022 Tencent Cloud. All rights reserved.

Page 109 of 360

Tencent Cloud EdgeOne

headers.values(): iterator;
The values() method obtains all values that are included in the Headers object. For valid return values, see
Iteration protocols.

Sample Code©2013-2022 Tencent Cloud. All rights reserved.

Page 110 of 360

Tencent Cloud EdgeOne

function handleEvent() {const headers = new Headers({'my-header-x': 'hello world',});
const response =headers,});

new Response('hello world',{

return response;}©2013-2022 Tencent Cloud. All rights reserved.

Page 111 of 360

Tencent Cloud EdgeOne

addEventListener('fetch', (event) => {event.respondWith(handleEvent(event));});

References
MDN documentation: Headers
Sample Functions: Protecting Data from Tampering
Sample Functions: Authenticating a Request Header
Sample Functions: Modifying a Response Header©2013-2022 Tencent Cloud. All rights reserved.

Page 112 of 360

Tencent Cloud EdgeOne

Request：Last updated 2024-05-11 15:35:51
The Request API represents an HTTP request. It is designed based on the standard Web API Request.
Note
In Edge Functions, you can obtain a Request object by using any of the following methods:
Create a Request object for the Fetch API by using the Request constructor.
Use the FetchEvent object event.request to obtain a Request object.

Constructor API©2013-2022 Tencent Cloud. All rights reserved.

Page 113 of 360

Tencent Cloud EdgeOne

const request = new Request(input: string | Request, init?: RequestInit)

Parameters
Parameter

Type

Required

Description

input

string | RequestYes

A URL string or a Request object.

options

RequestInit

No

Initial configuration items of the Requestname©2013-2022 Tencent Cloud. All rights reserved.

Page 114 of 360

Tencent Cloud EdgeOne

object.

RequestInit
The following table describes the initial configuration items of the Request object.
Name

Type

Required

Defaultvalue

methodstringNo

GET

headers

Headers

No

-

No

-

Description
Request method. Examples: GET
and POST .
Headers that you want to add to therequest.

string |Blob | ArrayBuffer
body| ArrayBufferView

Request body.

|ReadableStream
Redirect mode. Valid values:
redirect

stringNo

follow

manual , error , andfollow .

maxFollow

numberNo

12

The maximum number of redirects
allowed.
HTTP version. Valid values:

versionstringNo

HTTP/1.1

HTTP/1.0 , HTTP/1.1 , andHTTP/2.0 .
Specifies whether to copy the

copyHeadersbooleanNo-headers of the Request object.
This parameter is not in the Web
API specifications.

eo

RequestInitEoProperties

No-

Specifies the behavior that Edge
Functions adopts in processing therequest. This parameter is not in
the Web API specifications.

RequestInitEoProperties
This parameter specifies the behavior that Edge Functions adopts in processing the request. It is not in the Web API
specifications.
Parameter
name

Type

Required©2013-2022 Tencent Cloud. All rights reserved.

Description

Page 115 of 360

Tencent Cloud EdgeOne

resolveOverride

stringNo

Overrides the original domain name resolution for the
fetch request. You can specify a domain name or IP
address that meets the following requirements:
The IP address cannot contain a scheme or port number.
For an IPv6 address, you do not need to enclose it in apair of square brackets.

Image

ImageProperties

No

Image processing configurations

ImageProperties
fetch supports image processing. The configurations are the same as of site acceleration. For more information, see
Resizing and Converting Images.
Parameter

Type

Required

formatstringNo

longnumberNo

shortnumberNo

Specify the length of the short side, and automatically scale the longside (if not specified)width

numberNo

Specify the width, and automatically scale the height (if not specified)heightnumberNo

Specify the height, and automatically scale the width (if not specified)name

Description
Convert an image into a specified format. Valid values: jpg ,gif , png , bmp , webp , avif , jp2 , jxr , heif .
Specify the length of the long side, and automatically scale the shortside (if not specified)Attributes
body©2013-2022 Tencent Cloud. All rights reserved.

Page 116 of 360

Tencent Cloud EdgeOne// request.body
readonly body: ReadableStream;
Request body. For more information, see ReadableStream.

bodyUsed©2013-2022 Tencent Cloud. All rights reserved.

Page 117 of 360

Tencent Cloud EdgeOne// request.bodyUsed
readonly bodyUsed: boolean;
Indicates whether the request body is read.

headers©2013-2022 Tencent Cloud. All rights reserved.

Page 118 of 360

Tencent Cloud EdgeOne// request.headers
readonly headers: Headers;Request headers. For more information, see Headers.

method©2013-2022 Tencent Cloud. All rights reserved.

Page 119 of 360

Tencent Cloud EdgeOne// request.method
readonly method: string;
The request method. Default value: GET .

redirect©2013-2022 Tencent Cloud. All rights reserved.

Page 120 of 360

Tencent Cloud EdgeOne// request.redirect
readonly redirect: string;
The request redirect mode. Valid values: follow , error , and manual . Default value: manual .

maxFollow©2013-2022 Tencent Cloud. All rights reserved.

Page 121 of 360

Tencent Cloud EdgeOne// request.maxFollow
readonly maxFollow: number;
The maximum number of redirects.

url©2013-2022 Tencent Cloud. All rights reserved.

Page 122 of 360

Tencent Cloud EdgeOne// request.url
readonly url: string;
The request URL.

version©2013-2022 Tencent Cloud. All rights reserved.

Page 123 of 360

Tencent Cloud EdgeOne// request.version
readonly version: string;
The HTTP version that is used by the request.

eo©2013-2022 Tencent Cloud. All rights reserved.

Page 124 of 360

Tencent Cloud EdgeOne// request.version
readonly eo: IncomingRequestEoProperties;
Other information provided by Edge Functions about the current request. For more information, see
IncomingRequestEoProperties.
IncomingRequestEoProperties
The client request object event.request contains an eo attribute.
Name

Type

©2013-2022 Tencent Cloud. All rights reserved.

Description

ExamplePage 125 of 360

Tencent Cloud EdgeOne

geo

GeoProperties

Location of the client who initiates the-request.

GeoProperties
Location of the client who initiates the request.
Name

Type

Description

Exampleasn

number

ASN

132203countryName

stringCountry nameSingaporecountryCodeAlpha2stringcountryCodeAlpha3

stringISO-3611 alpha3 code of
the country

SGP

countryCodeNumericstringISO-3611 numeric code of
the country.

702

regionName

stringRegion name-regionCode

stringRegion code

AA-AA

cityName

stringCity namesingapore

latitudenumberLatitude1.29027

longitudenumberLongitude

103.851959

ISO-3611 alpha2 code of
the country

SG

Methods
Important
When using a method to obtain the request body, the size of the HTTP body is capped at 1 MB. If the threshold isexceeded, an OverSize exception is returned. In this case, we recommend that you use request.body to read therequest body in streaming mode. For more information, see ReadableStream.

arrayBuffer©2013-2022 Tencent Cloud. All rights reserved.

Page 126 of 360

Tencent Cloud EdgeOne

request.arrayBuffer(): Promise<ArrayBuffer>;
The arrayBuffer() method reads the request body and returns a promise that resolves with an ArrayBuffer.

blob©2013-2022 Tencent Cloud. All rights reserved.

Page 127 of 360

Tencent Cloud EdgeOne

request.blob(): Promise<Blob>;
The blob() method reads the request body and returns a promise that resolves with a Blob.

clone©2013-2022 Tencent Cloud. All rights reserved.

Page 128 of 360

Tencent Cloud EdgeOne

request.clone(copyHeaders?: boolean): Request;
The clone() method creates a clone of a request object.
Parameter
Parameter
name
copyHeadersType

Required

Description

booleanNo

Specifies whether to copy the request headers of the original object.
Default value: false . Valid values:©2013-2022 Tencent Cloud. All rights reserved.

Page 129 of 360

Tencent Cloud EdgeOne

true
Copy the request headers of the original object.
false
Reference the request headers of the original object.

json

request.json(): Promise<object>;©2013-2022 Tencent Cloud. All rights reserved.

Page 130 of 360

Tencent Cloud EdgeOne

The json() method reads the request body and returns a promise that resolves with the parsing result of the body text
as json .

text

request.text(): Promise<string>;
The text() method reads the request body and returns a promise that resolves with a String.

formData©2013-2022 Tencent Cloud. All rights reserved.

Page 131 of 360

Tencent Cloud EdgeOne

request.formData(): Promise<FormData>;
The formData() method takes a Response stream, reads it to completion, and returns a promise that resolves with a
FormData.

Parameter
Parameter nameType©2013-2022 Tencent Cloud. All rights reserved.

Required

Description

Page 132 of 360

Tencent Cloud EdgeOne

cookies

CookiesNo

A new Cookies object.

Sample Codeasync function handleRequest() {const request = new Request('https://www.tencentcloud.com/');const response = await fetch(request);
return response;©2013-2022 Tencent Cloud. All rights reserved.

Page 133 of 360

Tencent Cloud EdgeOne}
addEventListener('fetch', (event) => {event.respondWith(handleRequest());});

References
MDN documentation: Request
Sample Functions: Using the Cache API
Sample Functions: Performing Redirect Based on the Request Location©2013-2022 Tencent Cloud. All rights reserved.

Page 134 of 360

Tencent Cloud EdgeOne

Response：

Last updated 2024-05-07 16:15:40
The Response API represents the response to an HTTP request. It is designed based on the standard Web API
Response.
Note
In Edge Functions, you can obtain a Response object by using the following methods:
Create a Response object by using the Response constructor API. This object can be used as the value of the
response parameter in the event.respondWith method.
Use Fetch to obtain a Response object.

Constructor API©2013-2022 Tencent Cloud. All rights reserved.

Page 135 of 360

Tencent Cloud EdgeOne

const response = new Response(body?: string | ArrayBuffer | Blob | ReadableStream |Parameters
Parameter

Type

Required

Description

Yes

The body of the Response object.

string | ArrayBuffer | Blob |body

ReadableStream | null |undefined©2013-2022 Tencent Cloud. All rights reserved.

Page 136 of 360

Tencent Cloud EdgeOne

init

ResponseInit

No

The initial configuration items of the
Response object.

ResponseInit
Parameter

Type

Required

Description

statusnumberNo

The status code for the response.

No

The status message for the response. The maximum length
is 4,095 bytes. If the length exceeds the upper limit, thestatusText

stringextra content will be truncated.
headers

Headers

No

The headers associated with the response.

Attributes
body©2013-2022 Tencent Cloud. All rights reserved.

Page 137 of 360

Tencent Cloud EdgeOne// response.body
readonly body: ReadableStream;
The response body. For more information, see ReadableStream.

bodyUsed©2013-2022 Tencent Cloud. All rights reserved.

Page 138 of 360

Tencent Cloud EdgeOne// response.bodyUsed
readonly bodyUsed: boolean;
Indicates whether the response body is read.

headers©2013-2022 Tencent Cloud. All rights reserved.

Page 139 of 360

Tencent Cloud EdgeOne// response.headers
readonly headers: Headers;
The response headers. For more information, see Headers.

ok©2013-2022 Tencent Cloud. All rights reserved.

Page 140 of 360

Tencent Cloud EdgeOne// response.ok
readonly ok: boolean;
Indicates whether the response was successful. If the status code ranges from 200 to 299, the response was
successful.

status©2013-2022 Tencent Cloud. All rights reserved.

Page 141 of 360

Tencent Cloud EdgeOne// response.status
readonly status: number;
The status code for the response.

statusText©2013-2022 Tencent Cloud. All rights reserved.

Page 142 of 360

Tencent Cloud EdgeOne// response.statusText
readonly statusText: string;
The status message for the response.

url©2013-2022 Tencent Cloud. All rights reserved.

Page 143 of 360

Tencent Cloud EdgeOne// response.url
readonly url: string;
The URL of the response.

redirected©2013-2022 Tencent Cloud. All rights reserved.

Page 144 of 360

Tencent Cloud EdgeOne// response.redirected
readonly redirected: boolean;
Indicates whether the response is the result of a redirect.

redirectUrls©2013-2022 Tencent Cloud. All rights reserved.

Page 145 of 360

Tencent Cloud EdgeOne// response.redirectUrls
readonly redirectUrls: Array<String>
All URLs for redirection.

MethodsNote©2013-2022 Tencent Cloud. All rights reserved.

Page 146 of 360

Tencent Cloud EdgeOne

If the size of the HTTP body obtained by using a method exceeds 1 MB, the OverSize exception will be thrown. In
this case, we recommend that you use response.body to read the response body in streaming mode. For more
information, see ReadableStream.

arrayBuffer

response.arrayBuffer(): Promise<ArrayBuffer>;
The arrayBuffer() method takes a Response stream, reads it to completion, and returns a promise that resolves withan ArrayBuffer.

©2013-2022 Tencent Cloud. All rights reserved.

Page 147 of 360

Tencent Cloud EdgeOne

blob

response.blob(): Promise<Blob>;
The blob() method takes a Response stream, reads it to completion, and returns a promise that resolves with a Blob.

clone©2013-2022 Tencent Cloud. All rights reserved.

Page 148 of 360

Tencent Cloud EdgeOne

response.clone(copyHeaders?: boolean): Request;
The clone() method creates a clone of a response object.
Parameters
Parameter

Type

Required

Description

copyHeadersbooleanNo

Specifies whether to copy the response headers of the original
object. Default value: false . Valid values:true©2013-2022 Tencent Cloud. All rights reserved.

Page 149 of 360

Tencent Cloud EdgeOne

Copy the response headers of the original object.
false
Reference the response headers of the original object.

json

response.json(): Promise<object>;
The json() method takes a Response stream, reads it to completion, and returns a promise which resolves with theparsing result of the body text as json .

©2013-2022 Tencent Cloud. All rights reserved.

Page 150 of 360

Tencent Cloud EdgeOne

text

response.text(): Promise<string>;
The text() method takes a Response stream, reads it to completion, and returns a promise that resolves with a String.

formData©2013-2022 Tencent Cloud. All rights reserved.

Page 151 of 360

Tencent Cloud EdgeOne

response.formData(): Promise<FormData>;
The formData() method takes a Response stream, reads it to completion, and returns a promise that resolves with a
FormData.

Static Methods©2013-2022 Tencent Cloud. All rights reserved.

Page 152 of 360

Tencent Cloud EdgeOne

error

Response.error(): Response;
The error() method returns a new Response object that contains network error information.

redirect©2013-2022 Tencent Cloud. All rights reserved.

Page 153 of 360

Tencent Cloud EdgeOne

Response.redirect(url: string | URL, status?: number): Response;
The redirect() method returns a Response object resulting in a redirect to the specified URL.
Parameters
Parameter

Type

Required

Description

urlstringYes

Redirect URL

statusnumberNo

Status code for the response. Valid values: 301, 302,

©2013-2022 Tencent Cloud. All rights reserved.

Page 154 of 360

Tencent Cloud EdgeOne

303, 307, and 308. Default value: 302.

Sample Code

addEventListener('fetch', (event) => {const response = new Response('hello world');
event.respondWith(response);});©2013-2022 Tencent Cloud. All rights reserved.

Page 155 of 360

Tencent Cloud EdgeOne

References
MDN documentation: Response
Sample Functions: Returning an HTML Page
Sample Functions: Modifying a Response Header
Sample Functions: Performing an A/B Test

©2013-2022 Tencent Cloud. All rights reserved.

Page 156 of 360

Tencent Cloud EdgeOne

Streams
ReadableStream：

Last updated 2024-01-30 14:59:48
The ReadableStream API represents a readable stream or readable end. It is designed based on the standard Web
API ReadableStream.
Note:
A ReadableStream object cannot be constructed directly. You can use TransformStream to construct a
ReadableStream object.

Overview©2013-2022 Tencent Cloud. All rights reserved.

Page 157 of 360

Tencent Cloud EdgeOne// Use TransformStream to construct a ReadableStream object.
const { readable } = new TransformStream();Attributes©2013-2022 Tencent Cloud. All rights reserved.

Page 158 of 360

Tencent Cloud EdgeOne// readable.locked
readonly locked: boolean;
The locked attribute indicates whether a stream is locked.
Note:
A stream is locked in the following scenarios:
The stream has no more than one activated reader . Before the reader calls the releaseLock() method,
the stream is locked.
The stream is in being piped. The stream is locked until the piping ends.

©2013-2022 Tencent Cloud. All rights reserved.

Page 159 of 360

Tencent Cloud EdgeOne

Methods
Note:
Before you use any of the following methods, make sure that the stream is not locked. Otherwise, an exception isreturned.

getReaderreadable.getReader(options?: ReaderOptions): ReadableStreamDefaultReader | Readable©2013-2022 Tencent Cloud. All rights reserved.

Page 160 of 360

Tencent Cloud EdgeOne

The getReader() method creates a reader and locks the current stream until the reader calls thereleaseLock() method.
Parameters
Parameter

Type

Required

Description

options

ReaderOptions

Yes

The configuration items for generating the reader.

ReaderOptions
The following table describes the parameters of the ReaderOptions object.
Parameter

Type

Required

Description
Reader The type of the `reader`. Default value:
undefined. Valid values:mode

stringNo

undefined
Create a reader of the ReadableStreamDefaultReader type.
byob
Create a reader of the ReadableStreamBYOBReader type.

pipeThrough©2013-2022 Tencent Cloud. All rights reserved.

Page 161 of 360

Tencent Cloud EdgeOne

readable.pipeThrough(transformStream: TransformStream, options?: PipeToOptions): Re
The pipeThrough() method pipes the data of the current readable stream to the writable side of thetransformStream and returns the readable side of the transformStream .
Note:During the piping, the writable side of the current stream is locked.
Parameters
ParameterType©2013-2022 Tencent Cloud. All rights reserved.

Required

Description

Page 162 of 360

Tencent Cloud EdgeOne

transformStream

TransformStream

Yes

The destination to which the current stream is piped.

options

PipeToOptions

Yes

The configuration items for piping the stream.

PipeToOptions
The following table describes the configuration items for piping the stream.
Parameter

Type

Required

Description

preventClosebooleanNo

preventAbortbooleanNo

preventCancel

booleanNo

If the value is true, the writable stream is not closed when thereadable stream is incorrect.

signalAbortSignal

No

If `signal` is stopped, ongoing pipe operations are stopped.

If the value is true, the writable stream is not closed along withthe readable stream.
If the value is true, the writable stream is not stopped when an
exception occurs on the readable stream.

pipeTo©2013-2022 Tencent Cloud. All rights reserved.

Page 163 of 360

Tencent Cloud EdgeOne

readable.pipeTo(destination: WritableStream, options?: PipeToOptions): Promise<void
The pipeTo() method pipes the current readable stream to the destination writable stream.
Note:
During the piping, the destination of the current stream is locked.
Parameters
Parameter

Type

Required©2013-2022 Tencent Cloud. All rights reserved.

Description

Page 164 of 360

Tencent Cloud EdgeOne

destination

WritableStream

Yes

The writable stream.

options

PipeToOptions

Yes

The configuration items for piping the stream.

teereadable.tee(): [ReadableStream, ReadableStream];
The tee() method tees the current readable stream and returns two independent branches.

©2013-2022 Tencent Cloud. All rights reserved.

Page 165 of 360

Tencent Cloud EdgeOne

cancelreadable.cancel(reason?: string): Promise<string>;
The cancel() method ends the current stream.

References
MDN documentation: ReadableStream©2013-2022 Tencent Cloud. All rights reserved.

Page 166 of 360

Tencent Cloud EdgeOne

Sample Functions: Merging Resources and Responding in Streaming Mode
Sample Functions: Rewriting a m3u8 File and Configuring Authentication©2013-2022 Tencent Cloud. All rights reserved.

Page 167 of 360

Tencent Cloud EdgeOne

ReadableStreamBYOBReader：

Last updated 2024-01-30 15:05:35
The ReadableStreamBYOBReader API defines a reader for a readable stream. It is designed based on thestandard Web API ReadableStreamBYOBReader. BYOB is an abbreviation of bring your own buffer. A
ReadableStreamBYOBReader object allows to read data from streams and write the read data to the buffer, thereby
reducing replicas.
Note:
A ReadableStreamBYOBReader object cannot be constructed directly. You can use the
ReadableStream.getReader method to construct a ReadableStreamBYOBReader object.

Overview©2013-2022 Tencent Cloud. All rights reserved.

Page 168 of 360

Tencent Cloud EdgeOne// Use TransformStream to construct a ReadableStream object.
const { readable } = new TransformStream();// Use the ReadableStream object to obtain the reader.
const reader = readable.getReader({mode: 'byob',});©2013-2022 Tencent Cloud. All rights reserved.

Page 169 of 360

Tencent Cloud EdgeOne

Attributes// readable.locked
readonly locked: boolean;
The locked attribute returns a Promise object. If the stream is closed, the status of the Promise object isfulfilled . If an exception occurs on the stream or the lock on the reader is released, the status of the Promise
object is rejected .

©2013-2022 Tencent Cloud. All rights reserved.

Page 170 of 360

Tencent Cloud EdgeOne

Methods
read

reader.read(bufferView: ArrayBufferView): Promise<{value: ArrayBufferView, done: bo
The read() method reads data from the stream and writes the read data to the bufferView on the buffer.
Note:
You cannot initiate the next stream reading operation until the current stream reading operation ends.

©2013-2022 Tencent Cloud. All rights reserved.

Page 171 of 360

Tencent Cloud EdgeOne

Returned values
The reader.read method returns a Promise object that contains the read data and the reading status.
If a chunk is available, the Promise object is in the fulfilled status and contains an object in the { value:
theChunk, done: false } format.
If the stream is closed, the status of the Promise object is switched to fulfilled , and an object in the {value: theChunk, done: true } format is contained.
If an exception occurs on the stream, the Promise object is in the rejected status, and the relevant error
information is included.

cancel©2013-2022 Tencent Cloud. All rights reserved.

Page 172 of 360

Tencent Cloud EdgeOne

reader.cancel(reason?: string): Promise<string>;
The cancel() method closes the stream and ends the reading operation.

releaseLock©2013-2022 Tencent Cloud. All rights reserved.

Page 173 of 360

Tencent Cloud EdgeOne

reader.releaseLock(): void;
The releaseLock() method cancels the association with the stream and releases the lock on the stream.

References
MDN documentation: ReadableStreamBYOBReader©2013-2022 Tencent Cloud. All rights reserved.

Page 174 of 360

Tencent Cloud EdgeOne

ReadableStreamDefaultReader：

Last updated 2024-01-30 15:08:11
The ReadableStreamDefaultReader API defines a reader for a readable stream. It is designed based on thestandard Web APIs ReadableStreamDefaultReader.
Note:
A ReadableStreamDefaultReader object cannot be constructed directly. You can use the
ReadableStream.getReader method to construct a ReadableStreamDefaultReader object.

Overview©2013-2022 Tencent Cloud. All rights reserved.

Page 175 of 360

Tencent Cloud EdgeOne// Use TransformStream to construct a ReadableStream object.
const { readable } = new TransformStream();// Use the ReadableStream object to obtain the reader.
const reader = readable.getReader();

Attributes©2013-2022 Tencent Cloud. All rights reserved.

Page 176 of 360

Tencent Cloud EdgeOne

closed// reader.closed
readonly closed: Promise<void>;
The closed attribute returns a Promise object. If the stream is closed, the status of the Promise object isfulfilled . If an exception occurs on the stream or the lock on the reader is released, the status of the Promise
object is rejected .

©2013-2022 Tencent Cloud. All rights reserved.

Page 177 of 360

Tencent Cloud EdgeOne

Methods
read

reader.read(): Promise<{value: Chunk, done: boolean}>;
The read() method reads data from the stream.
Note:
You cannot initiate the next stream reading operation until the current stream reading operation ends.

©2013-2022 Tencent Cloud. All rights reserved.

Page 178 of 360

Tencent Cloud EdgeOne

Returned values
The reader.read method returns a Promise object that contains the read data Chunk and the reading status.
If a chunk is available, the Promise object is in the fulfilled status and contains an object in the { value:
theChunk, done: false } format.
If the stream is closed, the Promise object is in the fulfilled status and contains an object in the { value:
undefined, done: true } format.
If an exception occurs on the stream, the Promise object is in the rejected status, and the relevant error
information is included.
Chunk
The Chunk parameter indicates the data to be read from the stream.

©2013-2022 Tencent Cloud. All rights reserved.

Page 179 of 360

Tencent Cloud EdgeOne

type Chunk = string | ArrayBuffer | ArrayBufferView;

cancel©2013-2022 Tencent Cloud. All rights reserved.

Page 180 of 360

Tencent Cloud EdgeOne

reader.cancel(reason?: string): Promise<string>;
The cancel() method closes the stream and ends the reading operation.

releaseLock©2013-2022 Tencent Cloud. All rights reserved.

Page 181 of 360

Tencent Cloud EdgeOne

reader.releaseLock(): void;
The releaseLock() method cancels the association with the stream and releases the lock on the stream.

References
MDN documentation: ReadableStreamDefaultReader©2013-2022 Tencent Cloud. All rights reserved.

Page 182 of 360

Tencent Cloud EdgeOne

TransformStream：

Last updated 2024-01-30 15:32:47
A TransformStream consists of a readable stream and a writable stream. It is designed based on the standard Web
API TransformStream.

Constructor API©2013-2022 Tencent Cloud. All rights reserved.

Page 183 of 360

Tencent Cloud EdgeOne

const { readable, writable } = new TransformStream(transformer?: any, writableStrat

Parameters
Parameter

Type

Required

Description

transformer

any

No

This parameter is not supported. The values do not takeeffect and are ignored automatically.

writableStrategy

WritableStrategy

No

The strategy for the writable side.

©2013-2022 Tencent Cloud. All rights reserved.

Page 184 of 360

Tencent Cloud EdgeOne

WritableStrategy
Parameter

Type

Required

Description
The size of the writable buffer in bytes. Default value: 32K.

highWaterMark

numberYes

Maximum value: 256K. If you enter a value greater than 256K, thevalue is changed to 256K automatically.

Attributes
readable©2013-2022 Tencent Cloud. All rights reserved.

Page 185 of 360

Tencent Cloud EdgeOne

readonly readable: ReadableStream;
The readable stream. For more information, see ReadableStream.

writable©2013-2022 Tencent Cloud. All rights reserved.

Page 186 of 360

Tencent Cloud EdgeOne

readonly writable: WritableStream;
The writable stream. For more information, see WritableStream.

Sample Code©2013-2022 Tencent Cloud. All rights reserved.

Page 187 of 360

Tencent Cloud EdgeOne

async function handleEnterRoom() {// Generate readable streams and writeable streams.
const { readable, writable } = new TransformStream();// Fetch a remote resource.
const response = await fetch('https://www.tencentcloud.com/');// Respond to the client in streaming mode.
response.body.pipeTo(writable);return new Response(readable, response);}©2013-2022 Tencent Cloud. All rights reserved.

Page 188 of 360

Tencent Cloud EdgeOne

addEventListener('fetch', (event) => {event.respondWith(handleEvent(event));});

References
MDN documentation: TransformStream
Sample Functions: Merging Resources and Responding in Streaming Mode
Sample Functions: Rewriting a m3u8 File and Configuring Authentication©2013-2022 Tencent Cloud. All rights reserved.

Page 189 of 360

Tencent Cloud EdgeOne

WritableStream：

Last updated 2024-01-30 16:00:52
The WritableStream API represents a writable stream or writable side. It is designed based on the standard Web
API WritableStream.
Note:
A WritableStream object cannot be constructed directly. You can use TransformStream to construct a
WritableStream object.

Overview©2013-2022 Tencent Cloud. All rights reserved.

Page 190 of 360

Tencent Cloud EdgeOne// Use TransformStream to construct a WritableStream object.
const { writable } = new TransformStream();Attributes
locked©2013-2022 Tencent Cloud. All rights reserved.

Page 191 of 360

Tencent Cloud EdgeOne// writable.locked
readonly locked: boolean;
The locked attribute indicates whether the stream is locked.
Note:
A stream is locked in the following scenarios:
The stream has no more than one activated writer . Before the writer calls the releaseLock() method,
the stream is locked.
The stream is in being piped. The stream is locked until the piping ends.

©2013-2022 Tencent Cloud. All rights reserved.

Page 192 of 360

Tencent Cloud EdgeOne

highWaterMark// writable.highWaterMark
readonly highWaterMark: number;
The size of the writable buffer in bytes. Default value: 32K. Maximum value: 256K. If you enter a value greater than
256K, the value is changed to 256K automatically.

Methods©2013-2022 Tencent Cloud. All rights reserved.

Page 193 of 360

Tencent Cloud EdgeOne

Note:
Before you use any of the following methods, make sure that the stream is not locked. Otherwise, an exception isreturned.

getWriterwritable.getWriter(): WritableStreamDefaultWriter;
The getWriter() method creates a writer and locks the current stream until the writer calls the releaseLock() method.
For more information about the returned values, see WritableStreamDefaultWriter.

©2013-2022 Tencent Cloud. All rights reserved.

Page 194 of 360

Tencent Cloud EdgeOne

close

writable.close(): Promise<void>;
The close() method closes the current stream.

abort©2013-2022 Tencent Cloud. All rights reserved.

Page 195 of 360

Tencent Cloud EdgeOne

writable.abort(reason?: string): Promise<string>;
The abort() method stops the current stream.

References
MDN documentation: WritableStream
Sample Functions: Merging Resources and Responding in Streaming Mode©2013-2022 Tencent Cloud. All rights reserved.

Page 196 of 360

Tencent Cloud EdgeOne

Sample Functions: Rewriting a m3u8 File and Configuring Authentication©2013-2022 Tencent Cloud. All rights reserved.

Page 197 of 360

Tencent Cloud EdgeOne

WritableStreamDefaultWriter：

Last updated 2024-01-30 16:03:02
The WritableStreamDefaultWriter API defines a writer for a writable stream. It is designed based on the standard
Web API WritableStreamDefaultWriter.
Note:
A WritableStreamDefaultWriter object cannot be constructed directly. You can use the
WritableStream.getWriter method to construct a WritableStreamDefaultWriter object.

Overview©2013-2022 Tencent Cloud. All rights reserved.

Page 198 of 360

Tencent Cloud EdgeOne// Use TransformStream to construct a WritableStream object.
const { writable } = new TransformStream();// Use the WritableStream object to obtain the writer.
const writer = writable.getWriter();

Attributes©2013-2022 Tencent Cloud. All rights reserved.

Page 199 of 360

Tencent Cloud EdgeOne

closed// writer.closed
readonly closed: Promise<void>;
The closed attribute returns a Promise object. If the stream is closed, the status of the Promise object isfulfilled . If an exception occurs on the lock on the writer is released, the status of the Promise object isrejected .

ready©2013-2022 Tencent Cloud. All rights reserved.

Page 200 of 360

Tencent Cloud EdgeOne// writer.readyreadonly ready: Promise<void>;
The ready attribute returns a Promise object. When the size required by the internal queue of the stream changes from
non-positive to positive, the Promise object is in the fulfilled status, indicating that it no longer applies backpressure.

desiredSize©2013-2022 Tencent Cloud. All rights reserved.

Page 201 of 360

Tencent Cloud EdgeOne// writer.desiredSize
readonly desiredSize: number;
The desiredSize attribute returns the size required to fill the internal queue of the stream.

Methods
write©2013-2022 Tencent Cloud. All rights reserved.

Page 202 of 360

Tencent Cloud EdgeOne

writer.write(chunk: Chunk): Promise<void>;
The write() method writes the Chunk data to the stream.
Note:
You cannot call the write method to initiate the next stream writing operation until the current stream writing
operation ends.
Parameters
Parameter

Type

Required©2013-2022 Tencent Cloud. All rights reserved.

Description

Page 203 of 360

Tencent Cloud EdgeOne

chunk

Chunk

Yes

The chunk of data to be written to the stream.

Chunk
The Chunk parameter indicates the data to be written to the stream.

type Chunk = string | ArrayBuffer | ArrayBufferView;

close©2013-2022 Tencent Cloud. All rights reserved.

Page 204 of 360

Tencent Cloud EdgeOne

writer.close(): Promise<void>;
The close() method closes the current stream.

abort©2013-2022 Tencent Cloud. All rights reserved.

Page 205 of 360

Tencent Cloud EdgeOne

writer.abort(reason?: string): Promise<string>;
The abort() method stops the current stream.

releaseLock©2013-2022 Tencent Cloud. All rights reserved.

Page 206 of 360

Tencent Cloud EdgeOne

writer.releaseLock(): void;
The releaseLock() method cancels the association with the stream and releases the lock on the stream.

References
MDN documentation: WritableStreamDefaultWriter©2013-2022 Tencent Cloud. All rights reserved.

Page 207 of 360

Tencent Cloud EdgeOne

Web Crypto：

Last updated 2024-01-30 14:51:12
The Web Crypto API is designed based on the standard Web API Web Crypto API. The Web Crypto API provides aset of functions for common cryptographic operations. Performing cryptographic operations by using the Web Crypto
API is significantly faster than performing them purely in JavaScript.
Note:
The Crypto object cannot be constructed directly. It is globally injected during the runtime of edge functions.
Directly use the global crypto instance.

Overview©2013-2022 Tencent Cloud. All rights reserved.

Page 208 of 360

Tencent Cloud EdgeOne// Perform encoding.
const encodeContent = new TextEncoder().encode('hello world');// Use crypto to perform SHA-256 hashing. The resulting hash is a promise that fulf
const sha256Content = await crypto.subtle.digest({ name: 'SHA-256' },encodeContent);
const result = new Uint8Array(sha256Content);©2013-2022 Tencent Cloud. All rights reserved.

Page 209 of 360

Tencent Cloud EdgeOne

Attributes// crypto.subtle
readonly subtle: SubtleCrypto;
The Web Crypto API supports common cryptographic operations, such as hashing, signature signing and verification,and encryption and decryption. For more information, see SubtleCrypto.

Methods©2013-2022 Tencent Cloud. All rights reserved.

Page 210 of 360

Tencent Cloud EdgeOne

getRandomValues

crypto.getRandomValues(buffer: TypedArray): TypedArray;
The getRandomValues() method generates a random value, fills the buffer with the random value, and returns thebuffer.
Parameters
ParameterType©2013-2022 Tencent Cloud. All rights reserved.

Required

Description

Page 211 of 360

Tencent Cloud EdgeOne

buffer

Int8Array |Uint8Array |Uint8ClampedArray|Int16Array |Uint16Array |Int32Array|Uint32Array |BigInt64Array |BigUint64ArrayYes

The buffer of random values. The
value cannot exceed 65,536 bytes
in length. For more information,
see TypedArray.

randomUUID

crypto.randomUUID(): string;
The randomUUID() method generates a new random (version 4) UUID.

©2013-2022 Tencent Cloud. All rights reserved.

Page 212 of 360

Tencent Cloud EdgeOne

SubtleCrypto
The SubtleCrypto API supports common cryptographic operations, such as hashing, signature signing andverification, and encryption and decryption. For more information, see SubtleCrypto.
Note:
SubtleCrypto methods are classified into the following types based on features:
Encryption methods: encrypt/decrypt , sign/verify , and digest . Such methods can be used to
implement security-related features such as privacy and identity verification.
Key management methods: generateKey , deriveKey , and importKey/exportKey . Such methods
can be used to manage keys.

digest©2013-2022 Tencent Cloud. All rights reserved.

Page 213 of 360

Tencent Cloud EdgeOne

crypto.subtle.digest(algorithm: string | object, data: ArrayBuffer): Promise<ArrayB
The decrypt() method returns a Promise object that fulfills with the generated data digest (hash). For more information,see SubtleCrypto.digest.

encrypt©2013-2022 Tencent Cloud. All rights reserved.

Page 214 of 360

Tencent Cloud EdgeOne

crypto.subtle.encrypt(algorithm: object, key: CryptoKey, data: ArrayBuffer): Promis
The encrypt() method returns a Promise object that fulfills with the encrypted data. For more information, see
SubtleCrypto.encrypt.

decrypt©2013-2022 Tencent Cloud. All rights reserved.

Page 215 of 360

Tencent Cloud EdgeOne

crypto.subtle.decrypt(algorithm: object, key: CryptoKey, data: ArrayBuffer): Promis
The decrypt() method returns a Promise object that fulfills with the decrypted data. For more information, see
SubtleCrypto.decrypt.

sign©2013-2022 Tencent Cloud. All rights reserved.

Page 216 of 360

Tencent Cloud EdgeOne

crypto.subtle.sign(algorithm: string | object, key: CryptoKey, data: ArrayBuffer):
The sign() method returns a Promise object that fulfills with the signature. For more information, see
SubtleCrypto.sign.

verify©2013-2022 Tencent Cloud. All rights reserved.

Page 217 of 360

Tencent Cloud EdgeOne

crypto.subtle.verify(algorithm: string | object, key: CryptoKey, signature: BufferS
The verify() method returns a Promise object that fulfills with the signature verification result. For more information, see
SubtleCrypto.verify.

generateKey©2013-2022 Tencent Cloud. All rights reserved.

Page 218 of 360

Tencent Cloud EdgeOne

crypto.subtle.generateKey(algorithm: object, extractable: boolean, keyUsages: Array
The generateKey() method returns a Promise object that fulfills with a CryptoKey or a CryptoKeyPair. For more
information, see SubtleCrypto.generateKey.

deriveKey©2013-2022 Tencent Cloud. All rights reserved.

Page 219 of 360

Tencent Cloud EdgeOne

crypto.subtle.deriveKey(algorithm: object, baseKey: CryptoKey, derivedKeyAlgorithm:
The deriveKey() method returns a Promise object that fulfills with a CryptoKey. For more information, see
SubtleCrypto.deriveKey.

importKey©2013-2022 Tencent Cloud. All rights reserved.

Page 220 of 360

Tencent Cloud EdgeOne

crypto.subtle.importKey(format: string, keyData: BufferSource, algorithm: string |The importKey() method returns a Promise object that fulfills with a CryptoKey. For more information, see
SubtleCrypto.importKey.

exportKey©2013-2022 Tencent Cloud. All rights reserved.

Page 221 of 360

Tencent Cloud EdgeOne

crypto.subtle.exportKey(format: string, key: CryptoKey): Promise<ArrayBuffer>;
The exportKey() method returns a Promise object that fulfills with an ArrayBuffer containing the key. For more
information, see SubtleCrypto.exportKey.

deriveBits©2013-2022 Tencent Cloud. All rights reserved.

Page 222 of 360

Tencent Cloud EdgeOne

crypto.subtle.deriveBits(algorithm: object, baseKey: CryptoKey, length: integer): P
The deriveBits() method returns a Promise object that fulfills with an ArrayBuffer of pseudo-random bits. For more
information, see SubtleCrypto.deriveBits.

wrapKey©2013-2022 Tencent Cloud. All rights reserved.

Page 223 of 360

Tencent Cloud EdgeOne

crypto.subtle.wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapA
The wrapKey() method returns a Promise object that fulfills with an ArrayBuffer containing the wrapped key. For more
information, see SubtleCrypto.wrapKey.

unwrapKey©2013-2022 Tencent Cloud. All rights reserved.

Page 224 of 360

Tencent Cloud EdgeOne

crypto.subtle.unwrapKey(format: string, wrappedKey: ArrayBuffer, unwrappingKey: Cry
The unwrapKey() method returns a Promise object that fulfills with the unwrapped CryptoKey. For more information,see SubtleCrypto.unwrapKey.

CryptoKey©2013-2022 Tencent Cloud. All rights reserved.

Page 225 of 360

Tencent Cloud EdgeOne

A CryptoKey represents a key that is generated by using an encryption algorithm. For more information, see
CryptoKey. The CryptoKey object cannot be constructed directly. You can use the following methods to generate
CryptoKey objects:
crypto.subtle.generateKey
crypto.subtle.importKey
crypto.subtle.deriveKey
crypto.subtle.unwrapKey
The following table describes the CryptoKey attributes.
Attribute

Type

Readonly

Description

type

stringYes

The type of the key.

extractablebooleanYesSpecifies whether the key can be exported.

algorithm

objectYes

usagesArray<string>Yes

The algorithm for which this key can be used and the associatedparameters.
The usage of the key.

CryptoKeyPair
A CryptoKeyPair represents a key pair that is generated by using an encryption algorithm. For more information,
see CryptoKeyPair. The CryptoKeyPair object cannot be constructed directly. You can use the following method togenerate CryptoKeyPair objects:
crypto.subtle.generateKey
The following table describes the CryptoKeyPair attributes.
Attribute

Type

Readonly

Description

privateKey

CryptoKey

Yes

The private key. For encryption and decryption algorithms, this key isused for decryption. For signature signing and verification algorithms,
this key is used for signature signing.

publicKey

CryptoKey

Yes

The public key. For encryption and decryption algorithms, this key isused for encryption. For signature signing and verification algorithms,
this key is used for signature verification.

Supported Algorithms©2013-2022 Tencent Cloud. All rights reserved.

Page 226 of 360

Tencent Cloud EdgeOne

Edge Functions supports all algorithms that are defined in the WebCrypto specification. The following table describes
the algorithms.
Algorithm

encrypt()
decrypt()sign()
verify()wrapKey()
unwrapKey()

deriveKey()
deriveBits()

generateKey()

importKey()

exportKRSASSAPKCS1v1_5

-

✓

-

-

✓

✓

✓

RSA-PSS

-

✓

-

-

✓

✓

✓

RSAOAEP

✓

-

✓

-

✓

✓

✓

ECDSA

-

✓

-

-

✓

✓

✓

ECDH

-

-

-

✓

✓

✓

✓

HMAC

-

✓

-

-

✓

✓

✓

AES-CTR

✓

-

✓

-

✓

✓

✓

AES-CBC

✓

-

✓

-

✓

✓

✓

AESGCM

✓

-

✓

-

✓

✓

✓

AES-KW

-

-

✓

-

✓

✓

✓

HKDF

-

-

-

✓

-

✓

-

PBKDF2

-

-

-

✓

-

✓

-

SHA-1

-

-

-

-

-

-

-

SHA-256

-

-

-

-

-

-

-

SHA-384

-

-

-

-

-

-

-

SHA-512

-

-

-

-

-

-

-

MD5

-

-

-

-

-

-

-

Sample Code©2013-2022 Tencent Cloud. All rights reserved.

Page 227 of 360

Tencent Cloud EdgeOne

function uint8ArrayToHex(arr) {return Array.prototype.map.call(arr, (x) => ((`0${x.toString(16)}`).slice(-2)))}
async function handleEvent(event) {const encodeArr = TextEncoder().encode('hello world');// Execute MD5.
const md5Buffer = await crypto.subtle.digest({ name: 'MD5' }, encodeArr);// Generate a hexadecimal string.
const md5Str = uint8ArrayToHex(new Uint8Array(md5Buffer));©2013-2022 Tencent Cloud. All rights reserved.

Page 228 of 360

Tencent Cloud EdgeOne

const response = new Response(md5Str);
return response;}
addEventListener('fetch', async (event) => {event.respondWith(handleEvent(event));});

References
MDN documentation: Web Crypto API
MDN documentation: SubtleCrypto
MDN documentation: CryptoKey
MDN documentation: CryptoKeyPair
Sample Functions: Protecting Data from Tampering
Sample Functions: Rewriting a m3u8 File and Configuring Authentication
Sample Functions: Caching POST Requests©2013-2022 Tencent Cloud. All rights reserved.

Page 229 of 360

Tencent Cloud EdgeOne

Web standards：

Last updated 2023-12-13 11:13:40
Edge Functions designs a serverless code execution environment based on the V8 JavaScript engine and provides
the following standardized Web APIs.

JavaScript Standard Built-in Objects
Edge Functions supports all JavaScript standard built-in objects. For more information, see Standard built-in objects.

URL©2013-2022 Tencent Cloud. All rights reserved.

Page 230 of 360

Tencent Cloud EdgeOne

const urlInfo = new URL('https://www.tencentcloud.com/');The URL API is used to parse, construct, standardize, and encode URLs. For more information, see URL.

Blob

©2013-2022 Tencent Cloud. All rights reserved.

Page 231 of 360

Tencent Cloud EdgeOne

const blob = new Blob(['hello', 'world'], { type: 'text/plain' });The Blob API represents a file-like object of immutable and raw data. For more information, see Blob.

Base64btoa©2013-2022 Tencent Cloud. All rights reserved.

Page 232 of 360

Tencent Cloud EdgeOne

function btoa(data: string | ArrayBuffer | ArrayBufferView): string;
The btoa() method performs Base64 encoding. Unicode strings are not supported. For more information, see btoa().

atob©2013-2022 Tencent Cloud. All rights reserved.

Page 233 of 360

Tencent Cloud EdgeOne

function atob(data: string): string;
The atob() method performs Base64 decoding. Unicode strings are not supported. For more information, see atob().

btoaUTF8©2013-2022 Tencent Cloud. All rights reserved.

Page 234 of 360

Tencent Cloud EdgeOne

function btoaUTF8(data: string): string;
The btoaUTF8() method performs Base64 encoding. Unicode strings are supported.

atobUTF8©2013-2022 Tencent Cloud. All rights reserved.

Page 235 of 360

Tencent Cloud EdgeOne

function atobUTF8(data: string): string;
The atobUTF8() method performs Base64 decoding. Unicode strings are supported.

Timer©2013-2022 Tencent Cloud. All rights reserved.

Page 236 of 360

Tencent Cloud EdgeOne

setTimeout

setTimeout(func: function): number;
setTimeout(func: function, delay: number): number;
setTimeout(func: function, delay: number, ...args: any[]): number;
Functioning as an ordinary timer, it executes the designated function upon expiration. For more details, see
setTimeout.

clearTimeout©2013-2022 Tencent Cloud. All rights reserved.

Page 237 of 360

Tencent Cloud EdgeOne

clearTimeout(timeoutID: number): void;
It is an ordinary timer to clear the designated timeoutID . For more information, see clearTimeout.

setInterval©2013-2022 Tencent Cloud. All rights reserved.

Page 238 of 360

Tencent Cloud EdgeOne

setInterval(func: function): number;setInterval(func: function, delay: number): number;setInterval(func: function, delay: number, ...args: any[]): number;
Functioning as a recurring timer, it implemets the designated function upon expiration. For more information, see
setInterval.

clearInterval©2013-2022 Tencent Cloud. All rights reserved.

Page 239 of 360

Tencent Cloud EdgeOne

clearInterval(intervalID: number): void;
It is used to clear a recurring timer. For more details, seeclearInterval.

setImmediate©2013-2022 Tencent Cloud. All rights reserved.

Page 240 of 360

Tencent Cloud EdgeOne

setImmediate(func: function): number;
setImmediate(func: function, ...args: any[]): number;
Functioning as an immediate timer, it executes the designated function after the EDGE-FUNCTION stack has beencleared. For more information, see setImmediate.

clearImmediate©2013-2022 Tencent Cloud. All rights reserved.

Page 241 of 360

Tencent Cloud EdgeOne

clearImmediate(immediateID: number): void;
It is used to clear an immediate timer. For more information, see setImmediate.

EventTarget and Event
EventTarget©2013-2022 Tencent Cloud. All rights reserved.

Page 242 of 360

Tencent Cloud EdgeOne

const eventTarget = new EventTarget();The EventTarget API allows objects to publish and subscribe to events. For more information, see EventTarget.

Event©2013-2022 Tencent Cloud. All rights reserved.

Page 243 of 360

Tencent Cloud EdgeOne

const event = new Event('type name');The Event API represents a basic event. For more information, see Event.

AbortSignal and AbortController
AbortSignal©2013-2022 Tencent Cloud. All rights reserved.

Page 244 of 360

Tencent Cloud EdgeOne

const signal = AbortSignal.abort();The AbortSignal API represents a signal object that allows you to stop a request. For more information, see
AbortSignal.

AbortController©2013-2022 Tencent Cloud. All rights reserved.

Page 245 of 360

Tencent Cloud EdgeOne

const controller = new AbortController();
The AbortController API represents a controller object that allows you to stop a request. For more information, see
AbortController.

CompressionStream and DecompressionStream
CompressionStream©2013-2022 Tencent Cloud. All rights reserved.

Page 246 of 360

Tencent Cloud EdgeOne

const { readable, writable } = new CompressionStream('gzip');
CompressionStream supports compression methods including gzip , deflate , and br . For more details,
see CompressionStream.

DecompressionStream©2013-2022 Tencent Cloud. All rights reserved.

Page 247 of 360

Tencent Cloud EdgeOne

const { readable, writable } = new DecompressionStream('gzip');
DecompressionStream supports decompression methods including gzip , deflate , and br . For moredetails, see DecompressionStream.

©2013-2022 Tencent Cloud. All rights reserved.

Page 248 of 360

Tencent Cloud EdgeOne

ImagesImageProperties：

Last updated 2024-05-24 16:52:27
OrientationEdge functions support custom image processing behaviors when you initialize a Fetch request or
initializing a Request object, through the ImageProperties parameter in RequestInitEoProperties. ImageProperties is a
non-standard option not included in the Web APIs. Here is how to use it.
When you initialize a Fetch request, set the ImageProperties parameter as follows:©2013-2022 Tencent Cloud. All rights reserved.

Page 249 of 360

Tencent Cloud EdgeOne

addEventListener('fetch', (event) => {const response = fetch(event.request, { eo: { image: { format: "avif" } } });event.respondWith(response);});
When you initialize a Request object, set the ImageProperties parameter as follows:©2013-2022 Tencent Cloud. All rights reserved.

Page 250 of 360

Tencent Cloud EdgeOne

async function handleRequest() {const request = new Request("https://www.example.com/test.jpg", { eo: { image: {const response = await fetch(request);
return response;}
addEventListener('fetch', (event) => {event.respondWith(handleRequest());});©2013-2022 Tencent Cloud. All rights reserved.

Page 251 of 360

Tencent Cloud EdgeOne

Edge Functions support multiple image processing capabilities by setting different ImageProperties parameters. This
includes Image Format Conversion, Image Quality Conversion, Image Scaling, Image Cropping, with specificconfigurations as follows.

Format Conversion
By specifying the format parameter, the original image is converted to the specified format.
Parameter Name

formatType

stringRequired

Description

No

Convert the original image to a specified format. Supports for
jpg , gif , png , bmp , webp , avif , jp2 ,jxr , heif .

avoidSizeIncrease

booleanNo

When this parameter is set, if the processed image size
exceeds that of the original, the original image will be returned
without processing.

Example:©2013-2022 Tencent Cloud. All rights reserved.

Page 252 of 360

Tencent Cloud EdgeOne// Convert the original image to AVIF format.
eo: { image: { format: "avif" } }Quality Conversion
By specifying the quality parameter, the quality of the image is adjusted.
Parameter NameType

Required©2013-2022 Tencent Cloud. All rights reserved.

Description

Page 253 of 360

Tencent Cloud EdgeOne

qualitystring |numberNo

The absolute quality of the image, with a value range of 0 to100. Use the minimum value between the original image
quality and the specified quality. Append "!" after quality to
enforce the specified value, for example, "90!".

rquality

string |number

The relative quality of the image, with a value range of 0 to100, is based on the original image quality. For example, ifNothe original image quality is 80 and rquality is set to 80, theresulting processed image will have a quality of 64(calculated as 80x80%).
The minimum quality of the image, with a value range of 0 tolquality

string |numberNo100. Set the minimum value of the quality parameter for the
result image.
For example, if the original image quality is 85, and lquality is
set to 80, the quality of the processed image remains at 85.
For example, if the original image quality is 60, and lquality is
set to 80, the quality of the processed image will beenhanced to 80.

avoidSizeIncrease

booleanNo

When this parameter is set, if the processed image size
exceeds that of the original, the original image will be
returned without processing.

Note:
The quality conversion parameters have an order of precedence. By default, lquality > quality >rquality . If all are configured simultaneously, only the parameter with the highest priority takes effect.
Example:©2013-2022 Tencent Cloud. All rights reserved.

Page 254 of 360

Tencent Cloud EdgeOne// Set the absolute quality of the image to 80.
eo: { image: { quality: 80 } }// Set the relative quality of the image to 80.
eo: { image: { rquality: 80 } }// Set the minimum quality of the image to 80.
eo: { image: { lquality: 80 } }©2013-2022 Tencent Cloud. All rights reserved.

Page 255 of 360

Tencent Cloud EdgeOne

Image Scaling
Image scaling operations are controlled by the fit parameter. By setting different fit parameters, various
types of scaling operations can be achieved.
Parameter
Name

Type

Required

Description
Set different image scaling and cropping modes, with the following
supported values for the fit parameter:fit

stringNo

contain: (Default) Scale the image while maintaining its aspectratio.
cover: Scale the image without maintaining its aspect ratio
according to pixel values.
percent: Scale the image without maintaining its aspect ratio
according to a percentage value.

Note:
The behaviors corresponding to different fit parameters will be explained in detail below.

Proportional Scaling
When the fit parameter is not set or the fit parameter is set to contain , the image is scaled while
maintaining its aspect ratio.
Parameter
Name
width

height

long

short

Type

Required

Description

string |numberNo

Set the target image width to be scaled to width pixels. When only
the width parameter is set, the height is scaled proportionally.

string |numberstring |numberstring |number

No

No

No

Set the target image height to be scaled to height pixels. When only
the height parameter is set, the width is scaled proportionally.
Set the target image's long edge to be scaled to long pixels. Set the
short edge to be scaled proportionally.
Set the target image's short edge to be scaled to short pixels. Set
the long edge to be scaled proportionally.

Note:
The above parameters have an order of precedence, with long > short > ( width | height ). If multiple
parameters are set simultaneously, only the parameter with the highest priority takes effect.

©2013-2022 Tencent Cloud. All rights reserved.

Page 256 of 360

Tencent Cloud EdgeOne

If both width and height parameters are set simultaneously, they define the maximum dimensions ( widthand height ) for the thumbnail, with both width and height being scaled proportionally.
In addition to the above features, proportional scaling based on the number of pixels is also supported.
Parameter
Name
area

Type

Required

Description

string |numberNo

For proportional scaling, the total number of pixels in the scaled
image does not exceed area.

Example:©2013-2022 Tencent Cloud. All rights reserved.

Page 257 of 360

Tencent Cloud EdgeOne// Set proportional scaling based on the long edge, with the length of the scaled leo: { image: { long: 100 } }// Set proportional scaling based on the short edge, with the length of the scaledeo: { image: { short: 100 } }// Set proportional scaling based on the width, with the scaled width being 100 px.
eo: { image: { width: 100 } }// Set proportional scaling based on the height, with the scaled height being 100 p
eo: { image: { height: 100 } }©2013-2022 Tencent Cloud. All rights reserved.

Page 258 of 360

Tencent Cloud EdgeOne// Set proportional scaling based on both height and width, with the maximum scaledeo: { image: { width: 100, height: 100 } }// Set proportional scaling based on the total number of pixels, with the total sca
eo: { image: { area: 10000 } }Non-Proportional Scaling
When the fit parameter is set to cover , the image is scaled without maintaining its aspect ratio according to
pixel values.
Parameter
Name
width

heightType

Required

Description

string |numberNo

Set the target image width to be scaled to width pixels.

No

Set the target image height to be scaled to height pixels.

string |numberNote:
In this mode, both the width and height parameters must be set simultaneously. If only one is set, the image
will be processed to either width x width or height x height .
Example:©2013-2022 Tencent Cloud. All rights reserved.

Page 259 of 360

Tencent Cloud EdgeOne// Set non-aspect ratio scaling based on pixel values, scaling the width to 100 px
eo: { image: { fit: 'cover', width: 100, height: 100 } }When the fit parameter is set to percent , the image is scaled without maintaining its aspect ratio according
to a percentage value.
Parameter
Name
width

Type

Required

Description

string |numberNo

Set the target image width to be scaled to width%, with a value
range of 0 to 100. When only the width parameter is set, the height©2013-2022 Tencent Cloud. All rights reserved.

Page 260 of 360

Tencent Cloud EdgeOne

remains unchanged.

heightstring |numberNo

Set the target image height to be scaled to height%, with a value
range of 0 to 100. When only the height parameter is set, the width
remains unchanged.

Note:
In this mode, the width and height parameters operate independently. If both width and height are
set simultaneously, the image will be processed to width% x height% .
Example:©2013-2022 Tencent Cloud. All rights reserved.

Page 261 of 360

Tencent Cloud EdgeOne// Set non-proportional scaling based on width percentage, with the scaled width beeo: { image: { fit: 'pencent', width: 50 } }// Set non-proportional scaling based on height percentage, with the scaled height
eo: { image: { fit: 'pencent', height: 50 } }// Set non-proportional scaling based on both width and height percentages, with theo: { image: { fit: 'pencent', width: 50, height: 50 } }Image Cropping
Image cropping is controlled by the fit parameter. By setting different fit parameters, various types ofcropping operations can be achieved.
Parameter
Name

fit

Type

stringRequired

Description
Set different image scaling and cropping modes, with thefollowing supported values for the fit parameter:No

cut: Perform cropping to the image.
crop: Perform scaling and cropping to the image.

Note:
The behaviors corresponding to different fit parameters will be explained in detail below.

Original Image Cropping
When the fit parameter is set to cut , the original image is cropped.
Parameter
Name

width

heightType

string | number

string | number

Required

Description

No

Crop the target image to a width of width pixels. When
only the width parameter is set, the height remains
unchanged.

No

Crop the target image to a height of height pixels.
When only the height parameter is set, the width
remains unchanged.

gravitystring | { [key: string]:
number | string }©2013-2022 Tencent Cloud. All rights reserved.

No

The anchor point for image cropping. Can be set to 3x3
grid orientation values or coordinate object.
For orientation values, see the 3x3 Grid Orientation
Diagram.

Page 262 of 360

Tencent Cloud EdgeOne

The coordinate object is in the form of { x: 100, y: 100 }.
x represents a horizontal offset of x pixels from the topleft corner of the image rightwards. y represents a
vertical offset of y pixels from the top-left corner of theimage downwards.

Note:
If the gravity parameter is not set, the default cropping will occur at the top-left corner (northwest).
Example:©2013-2022 Tencent Cloud. All rights reserved.

Page 263 of 360

Tencent Cloud EdgeOne// Set to perform original cropping based on width, with the cropped width being 10
eo: { image: { fit: 'cut', width: 100 } }// Set to perform original cropping based on height, with the cropped height beingeo: { image: { fit: 'cut', height: 100 } }// Set to perform original cropping based on both width and height, with the croppeeo: { image: { fit: 'cut', width: 100, height: 100 } }// Set to perform original cropping based on both width and height, specifying theeo: { image: { fit: 'cut', width: 100, height: 100, gravity:'center' } }// Set to perform original cropping based on both width and height, specifying theeo: { image: { fit: 'cut', width: 100, height: 100, gravity: { x: 100, y: 100 } }Scaled Cropping
When the fit parameter is set to crop , the image is scaled and cropped.
Parameter
Name

Type

Required

Description

width

string |numberNo

Set the target image width to be cropped to width pixels. When only
the width parameter is set, the height remains unchanged.

heightstring |numberNo

Set the target image height to be cropped to height pixels. When
only the height parameter is set, the width remains unchanged.

gravitystring

No

The anchor point for image cropping. Can be set to 3x3 gridorientation values. For orientation values, see the 3x3 Grid
Orientation Diagram.

Note:
In this mode, the gravity parameter must be set to 3x3 grid orientation values. If the gravity parameter is
not set, it defaults to be cropped at the center point (center).
Example:©2013-2022 Tencent Cloud. All rights reserved.

Page 264 of 360

Tencent Cloud EdgeOne// Set to perform scaled cropping based on width, with the cropped width being 100
eo: { image: { fit: 'crop', width: 100 } }// Set to perform scaled cropping based on height, with the cropped height being 10
eo: { image: { fit: 'crop', height: 100 } }// Set to perform scaled cropping based on both width and height, with the cropped
eo: { image: { fit: 'crop', width: 100, height: 100 } }// Set to perform scaled cropping based on both width and height, specifying an anc
eo: { image: { fit: 'crop', width: 100, height: 100, gravity:'northwest' } }©2013-2022 Tencent Cloud. All rights reserved.

Page 265 of 360

Tencent Cloud EdgeOne

3x3 Grid Orientation Diagram
The 3x3 grid orientation diagram provides positional references for various image operations. The red dots serve as
origin points for each region (after regions being selected via the gravity parameter, displacement operations
reference the respective origins).

©2013-2022 Tencent Cloud. All rights reserved.

Page 266 of 360

Tencent Cloud EdgeOne

Sample Functions
Returning an HTML Page：

Last updated 2024-01-25 14:29:07
In this example, an edge function is used to generate an HTML page, and the HTML page is accessed and previewed
from a browser.

Sample Code©2013-2022 Tencent Cloud. All rights reserved.

Page 267 of 360

Tencent Cloud EdgeOne

const html = `<!DOCTYPE html><body><h1>Hello World</h1><p>This markup was generated by TencentCloud Edge Functions.</p></body>`;async function handleRequest(request) {return new Response(html, {headers: {©2013-2022 Tencent Cloud. All rights reserved.

Page 268 of 360

Tencent Cloud EdgeOne'content-type': 'text/html; charset=UTF-8','x-edgefunctions-test': 'Welcome to use Edge Functions.',},});}
addEventListener('fetch', event => {event.respondWith(handleRequest(event.request));});Sample Preview
In the address bar of the browser, enter a URL that matches a trigger rule of the edge function to preview the effect of
the sample code.

References
Runtime APIs: addEventListener
Runtime APIs: Response
Runtime APIs: FetchEvent©2013-2022 Tencent Cloud. All rights reserved.

Page 269 of 360

Tencent Cloud EdgeOne

Returning a JSON Object：

Last updated 2024-01-25 14:26:56
In this example, an edge function is used to generate a JSON object, and the JSON object is accessed andpreviewed from a browser.

Sample Code©2013-2022 Tencent Cloud. All rights reserved.

Page 270 of 360

Tencent Cloud EdgeOne

const data = {content: 'hello world',};
async function handleRequest(request) {// Convert the JSON object to the String format.
const result = JSON.stringify(data, null, 2);
return new Response(result, {headers: {'content-type': 'application/json; charset=UTF-8',©2013-2022 Tencent Cloud. All rights reserved.

Page 271 of 360

Tencent Cloud EdgeOne

},
});
}
addEventListener('fetch', event => {return event.respondWith(handleRequest(event.request));});Sample Preview
In the address bar of the browser, enter a URL that matches a trigger rule of the edge function to preview the effect of
the sample code.

References
Runtime APIs: addEventListener
Runtime APIs: Response©2013-2022 Tencent Cloud. All rights reserved.

Page 272 of 360

Tencent Cloud EdgeOne

Fetch Remote Resources：

Last updated 2024-01-25 14:21:18
In this example, the Fetch API is called to fetch a remote jQuery.js resource and send the resource to a client inresponse to a request from the client.

Sample Code©2013-2022 Tencent Cloud. All rights reserved.

Page 273 of 360

Tencent Cloud EdgeOne

async function handleRequest(request) {// Fetch a remote resource.
const response = await fetch('https://static.cloudcachetci.com/qcloud/main/script
return response;}
addEventListener('fetch', event => {return event.respondWith(handleRequest(event.request));});©2013-2022 Tencent Cloud. All rights reserved.

Page 274 of 360

Tencent Cloud EdgeOne

Sample Preview
In the address bar of the browser, enter a URL that matches a trigger rule of the edge function to preview the effect of
the sample code.

References
Runtime APIs: Fetch©2013-2022 Tencent Cloud. All rights reserved.

Page 275 of 360

Tencent Cloud EdgeOne

Authenticating a Request Header：

Last updated 2024-01-25 11:43:50
This example demonstrates how to use an edge function to perform simple permission control by verifying the value ofthe x-custom-token request header. If the value is token-123456, access is allowed. Otherwise, access isdenied.

Sample Code©2013-2022 Tencent Cloud. All rights reserved.

Page 276 of 360

Tencent Cloud EdgeOne

async function handleRequest(request) {const token = request.headers.get('x-custom-token');if (token === 'token-123456') {return new Response('hello world');}// Incorrect key supplied. Reject the request.
return new Response('Sorry, you have supplied an invalid token.', {status: 403,});

©2013-2022 Tencent Cloud. All rights reserved.

Page 277 of 360

Tencent Cloud EdgeOne}
addEventListener('fetch', event => {event.respondWith(handleRequest(event.request));});Sample Preview
In the address bar of the browser, enter a URL that matches a trigger rule of the edge function to preview the effect of
the sample code.
If authentication fails, access is denied.

If authentication is successful, access is allowed.

©2013-2022 Tencent Cloud. All rights reserved.

Page 278 of 360

Tencent Cloud EdgeOne

References
Runtime APIs: Headers
Runtime APIs: Response©2013-2022 Tencent Cloud. All rights reserved.

Page 279 of 360

Tencent Cloud EdgeOne

Modifying a Response Header：

Last updated 2023-11-24 15:10:13
This example uses the Fetch API to implement a reverse proxy for the domain name www.example.com of the site,and sets the HTTP response headers through Edge functions to achieve CORS (Cross-Origin Resource Sharing).

Sample Code©2013-2022 Tencent Cloud. All rights reserved.

Page 280 of 360

Tencent Cloud EdgeOne

async function handleRequest(event) {const { request } = event;const urlInfo = new URL(request.url);
const proxyRequest = new Request(`https://www.example.com${urlInfo.pathname}${urlmethod: request.method,body: request.body,headers: request.headers,
copyHeaders: true,});
proxyRequest.headers.set('Host', 'www.example.com');©2013-2022 Tencent Cloud. All rights reserved.

Page 281 of 360

Tencent Cloud EdgeOne// fetch reverse proxy
const response = await fetch(proxyRequest);/** Add custom response headers **/// Specify which origins are allowed to access resources
response.headers.append('Access-Control-Allow-Origin', '*');// Specify which HTTP methods (such as GET, POST, etc.) are allowed to access res
response.headers.append('Access-Control-Allow-Methods', 'GET,POST');// Specify which HTTP headers can appear in the request header
response.headers.append('Access-Control-Allow-Headers', 'Authorization');// How long the result of the pre-flight request can be cachedresponse.headers.append('Access-Control-Max-Age', '86400');/** Delete response headers **/response.headers.delete('X-Cache');return response;}
addEventListener('fetch', event => {event.respondWith(handleRequest(event));});

Sample Preview
In the address bar of the browser, enter a URL that matches a trigger rule of the edge function to preview the effect of
the sample code.

©2013-2022 Tencent Cloud. All rights reserved.

Page 282 of 360

Tencent Cloud EdgeOne

References
Runtime APIs: Headers
Runtime APIs: Response©2013-2022 Tencent Cloud. All rights reserved.

Page 283 of 360

Tencent Cloud EdgeOne

Performing an A/B Test：

Last updated 2023-09-11 17:51:22
In this example, cookies are used to store session information and perform A/B testing on requests. This example
demonstrates how to use an edge function to perform A/B testing.

Sample Code©2013-2022 Tencent Cloud. All rights reserved.

Page 284 of 360

Tencent Cloud EdgeOne// cookie nameconst COOKIE_NAME = 'ABTest';// cookie value
const VALUE_A = 'index-a.html';
const VALUE_B = 'index-b.html';// Root path, the origin must exist this path, and under this path, there are files
const BASE_PATH = '/abtest';
async function handleRequest(request) {©2013-2022 Tencent Cloud. All rights reserved.

Page 285 of 360

Tencent Cloud EdgeOne

const urlInfo = new URL(request.url);// Judge the URL path, if accessing non-abtest resources, directly responded.
if (!urlInfo.pathname.startsWith(BASE_PATH)) {return fetch(request);}// Collected the current request's Cookie.
const cookies = new Cookies(request.headers.get('cookie'));const abTestCookie = cookies.get(COOKIE_NAME);
const cookieValue = abTestCookie?.value;// If the Cookie value is A test, Return index-a.html.
if (cookieValue === VALUE_A) {urlInfo.pathname = `/${BASE_PATH}/${cookieValue}`;return fetch(urlInfo.toString());}// If the Cookie value is B test, Return index-b.html.
if (cookieValue === VALUE_B) {urlInfo.pathname = `/${BASE_PATH}/${cookieValue}`;return fetch(urlInfo.toString());}// If the Cookie information does not exist, randomly grant the current request t
const testValue = Math.random() < 0.5 ? VALUE_A : VALUE_B;
urlInfo.pathname = `/${BASE_PATH}/${testValue}`;const response = await fetch(urlInfo.toString());
cookies.set(COOKIE_NAME, testValue, { path: '/', max_age: 60 });response.headers.set('Set-Cookie', getSetCookie(cookies.get(COOKIE_NAME)));
return response;}// Concatenate Set-Cookie.
function getSetCookie(cookie) {const cookieArr = [`${encodeURIComponent(cookie.name)}=${encodeURIComponent(cookie.value)}`,];const key2name = {expires: 'Expires',max_age: 'Max-Age',domain: 'Domain',
path: 'Path',©2013-2022 Tencent Cloud. All rights reserved.

Page 286 of 360

Tencent Cloud EdgeOne

secure: 'Secure',
httponly: 'HttpOnly',samesite: 'SameSite',};
Object.keys(key2name).forEach(key => {if (cookie[key]) {cookieArr.push(`${key2name[key]}=${cookie[key]}`);}});
return cookieArr.join('; ');}addEventListener('fetch', event => {event.respondWith(handleRequest(event.request));});Sample Preview
In the address bar of the browser, enter a URL that matches a trigger rule of the edge function to preview the effect of
the sample code.

©2013-2022 Tencent Cloud. All rights reserved.

Page 287 of 360

Tencent Cloud EdgeOne

References
Runtime APIs: Cookies
Runtime APIs: Response©2013-2022 Tencent Cloud. All rights reserved.

Page 288 of 360

Tencent Cloud EdgeOne

Setting Cookies：

Last updated 2023-09-11 17:49:21
In this example, cookies are used to count the number of access requests. When a browser accesses the Edge
Functions service, the number of access requests is increased by 1.

Sample Code©2013-2022 Tencent Cloud. All rights reserved.

Page 289 of 360

Tencent Cloud EdgeOne// cookie nameconst COOKIE_NAME = 'count';
async function handleRequest(request) {// collected the current requests' Cookies and resolution into scope
const cookies = new Cookies(request.headers.get('cookie'));const cookieCount = cookies.get(COOKIE_NAME);// count increment
const count = Number(cookieCount && cookieCount.value || 0) + 1;// update Cookie's countcookies.set(COOKIE_NAME, String(count));©2013-2022 Tencent Cloud. All rights reserved.

Page 290 of 360

Tencent Cloud EdgeOne

const response = new Response(`The count is: ${count}`);// setting responded cookies
response.headers.set('Set-Cookie', getSetCookie(cookies.get(COOKIE_NAME)));
return response;}// concatenate Set-Cookie
function getSetCookie(cookie) {const cookieArr = [`${encodeURIComponent(cookie.name)}=${encodeURIComponent(cookie.value)}`,];const key2name = {expires: 'Expires',max_age: 'Max-Age',domain: 'Domain',
path: 'Path',secure: 'Secure',
httponly: 'HttpOnly',samesite: 'SameSite',};
Object.keys(key2name).forEach(key => {if (cookie[key]) {cookieArr.push(`${key2name[key]}=${cookie[key]}`);}});
return cookieArr.join('; ');}addEventListener('fetch', (event) => {event.respondWith(handleRequest(event.request));});Sample Preview
In the address bar of the browser, enter a URL that matches a trigger rule of the edge function to preview the effect of
the sample code.

©2013-2022 Tencent Cloud. All rights reserved.

Page 291 of 360

Tencent Cloud EdgeOne

References
Runtime APIs: Cookies
Runtime APIs: Response
Runtime APIs: Request©2013-2022 Tencent Cloud. All rights reserved.

Page 292 of 360

Tencent Cloud EdgeOne

Performing Redirect Based on the Request
Location：

Last updated 2023-11-24 15:08:21
This example implements automatic redirection to the Target url of the region belonging to the Client by judging theregion of the Client. It realizes the delivery of requests based on the region of the Client through Edge functions.

Sample Code©2013-2022 Tencent Cloud. All rights reserved.

Page 293 of 360

Tencent Cloud EdgeOne// The collection of URLs in all regions.
const urls = {CN: 'https://www.example.com/zh-CN',
US: 'https://www.example.com/en-US',};// The default redirect URL.
const defaultUrl = 'https://www.example.com/en-US';/*** Redirect to the target URL based on the region of the current request.

©2013-2022 Tencent Cloud. All rights reserved.

Page 294 of 360

Tencent Cloud EdgeOne* @param { Request } request*/
function handleRequest(request) {// Obtain the region of the current request.
const alpha2code = request.eo.geo.countryCodeAlpha2;// The target URL that you want to use for redirection.
const url = urls[alpha2code] || defaultUrl;
return Response.redirect(url, 302);}
addEventListener('fetch', event => {event.respondWith(handleRequest(event.request));});Sample Preview
In the address bar of the browser, enter a URL that matches a trigger rule of the edge function to preview the effect of
the sample code.

©2013-2022 Tencent Cloud. All rights reserved.

Page 295 of 360

Tencent Cloud EdgeOne

References
Runtime APIs: Request
Runtime APIs: Response©2013-2022 Tencent Cloud. All rights reserved.

Page 296 of 360

Tencent Cloud EdgeOne

Using the Cache API：

Last updated 2024-01-25 11:42:05
In this sample edge function, the Fetch API is called to fetch a remote jQuery.js resource, and the Cache API is calledto cache the resource to an EdgeOne edge node. The cache duration is set to 10s.

Sample Code©2013-2022 Tencent Cloud. All rights reserved.

Page 297 of 360

Tencent Cloud EdgeOne

async function fetchJquery(event, request) {const cache = caches.default;// If the resource is not found in the cache, fetch the resource from the origin
let response = await fetch(request);// Add the Cache-Control field to the response header and set the cache duration
response.headers.append('Cache-Control', 's-maxage=10');event.waitUntil(cache.put(request, response.clone()));// Add an identifier indicating that the resource is not found in the cache to th
response.headers.append('x-edgefunctions-cache', 'miss');©2013-2022 Tencent Cloud. All rights reserved.

Page 298 of 360

Tencent Cloud EdgeOne

return response;}
async function handleEvent(event) {// The resource URL, which is also used as the cache key.
const request = new Request('https://static.cloudcachetci.com/qcloud/main/scripts// Obtain the default cache instance.
const cache = caches.default;try {// Fetch the associated resource from the cache. If the resource is already cac
let response = await cache.match(request);// If the resource is not found in the cache, re-fetch the remote resource.
if (!response) {return fetchJquery(event, request);}// Add an identifier indicating that the resource is found in the cache to the
response.headers.append('x-edgefunctions-cache', 'hit');return response;} catch (e) {await cache.delete(request);// If the cache duration of the resource times out or another error occurs, rereturn fetchJquery(event, request);}}
addEventListener('fetch', (event) => {event.respondWith(handleEvent(event));});

Sample Preview
In the address bar of the browser, enter a URL that matches a trigger rule of the edge function to preview the effect of
the sample code.
The resource is not found in the cache.

©2013-2022 Tencent Cloud. All rights reserved.

Page 299 of 360

Tencent Cloud EdgeOne

The resource is found in the cache.

References
Runtime APIs: Cache
Runtime APIs: Fetch
Runtime APIs: FetchEvent
Runtime APIs: Response©2013-2022 Tencent Cloud. All rights reserved.

Page 300 of 360

Tencent Cloud EdgeOne

Caching POST Requests：

Last updated 2024-01-25 11:39:35
In this example, an SHA-256 signature is calculated for the request body of a POST request and used as a part of thecache key, and the Cache API is called to cache the response content. If the content is already stored in the cache,the cached content is sent to the client. Otherwise, the Fetch API is called to initiate a subrequest to fetch a remoteresource. This example demonstrates how to use an edge function to cache POST requests.

Sample Code©2013-2022 Tencent Cloud. All rights reserved.

Page 301 of 360

Tencent Cloud EdgeOne

function uint8ArrayToHex(arr) {return Array.prototype.map.call(arr, (x) => (('0' + x.toString(16)).slice(-2))).j}// The SHA-256 signature digest.
async function sha256(message) {const msgBuffer = new TextEncoder().encode(message);const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);
return uint8ArrayToHex(new Uint8Array(hashBuffer));}©2013-2022 Tencent Cloud. All rights reserved.

Page 302 of 360

Tencent Cloud EdgeOne

async function fetchContent(event, cacheKey) {const cache = caches.default;// If the resource is not found in the cache, fetch the resource from the origin
const response = await fetch(event.request);// Add the Cache-Control field to the response header and specify the cache durat
response.headers.set('Cache-Control', 's-maxage=10');event.waitUntil(cache.put(cacheKey, response.clone()));// Add an identifier indicating that the resource is not found in the cache to th
response.headers.append('x-edgefunctions-cache', 'miss');
return response;}
async function handleRequest(event) {const request = event.request;
const body = await request.clone().text();// // Calculate the hash value based on the request body.
const hash = await sha256(body);// Use the hash value that is calculated based on the request body as a part of t
const cacheKey = `${request.url}${hash}`;const cache = caches.default;try {// Fetch the associated response content from the cache.
let response = await cache.match(cacheKey);if (!response) {return fetchContent(event, cacheKey);}// Add an identifier indicating that the resource is found in the cache to the
response.headers.append('x-edgefunctions-cache', 'hit');return response;} catch (error) {await cache.delete(cacheKey);// If the cache duration of the resource times out or the resource is not foundreturn fetchContent(event, cacheKey);}©2013-2022 Tencent Cloud. All rights reserved.

Page 303 of 360

Tencent Cloud EdgeOne

return response;}
addEventListener('fetch', (event) => {try {const request = event.request;// Process a POST request.
if (request.method.toUpperCase() === 'POST') {return event.respondWith(handleRequest(event));}// Non-POST request.
return event.respondWith(fetch(request));} catch (e) {return event.respondWith(new Response('Error thrown ' + e.message));}});

Sample Preview
In the address bar of the browser, enter a URL that matches a trigger rule of the edge function to preview the effect of
the sample code.
The resource is not found in the cache.

The resource is found in the cache.

©2013-2022 Tencent Cloud. All rights reserved.

Page 304 of 360

Tencent Cloud EdgeOne

References
Runtime APIs: Fetch
Runtime APIs: Cache
Runtime APIs: Web Crypto©2013-2022 Tencent Cloud. All rights reserved.

Page 305 of 360

Tencent Cloud EdgeOne

Responding in Streaming Mode：

Last updated 2024-01-25 11:36:31
In this example, the Fetch API is called to fetch a remote jQuery.js resource, and the resource is sent to a client instreaming mode in response to a request from the client.

Sample Code©2013-2022 Tencent Cloud. All rights reserved.

Page 306 of 360

Tencent Cloud EdgeOne

async function handleRequest(request) {const response = await fetch('https://static.cloudcachetci.com/qcloud/main/script
if (response.status !== 200) {return response;}// Generate readable streams and writeable streams.
const { readable, writable } = new TransformStream();// Respond to the client in streaming mode.
response.body.pipeTo(writable);©2013-2022 Tencent Cloud. All rights reserved.

Page 307 of 360

Tencent Cloud EdgeOne

return new Response(readable, response);}
addEventListener('fetch', event => {event.respondWith(handleRequest(event.request));});Sample Preview
In the address bar of the browser, enter a URL that matches a trigger rule of the edge function to preview the effect of
the sample code.

References
Runtime APIs: TransformStream
Runtime APIs: Response©2013-2022 Tencent Cloud. All rights reserved.

Page 308 of 360

Tencent Cloud EdgeOne

Merging Resources and Responding in
Streaming Mode：

Last updated 2024-01-25 11:35:14
In this example, three video clips are merged into one video, and the merged video is played on a client based on theorder in which the video clips are merged. This example demonstrates how to use an edge function to fetch multiple
remote resources, read and merge the resources in streaming mode, and respond to a client request by using themerged resource in streaming mode.

Sample Code©2013-2022 Tencent Cloud. All rights reserved.

Page 309 of 360

Tencent Cloud EdgeOne

async function combine(readableVideos, destination) {for (const readable of readableVideos) {// Send a streaming response.
await readable.pipeTo(destination, {preventClose: true});}
const writer = destination.getWriter();
writer.close();writer.releaseLock();©2013-2022 Tencent Cloud. All rights reserved.

Page 310 of 360

Tencent Cloud EdgeOne}
async function handleRequest(request) {// The URLs of the video clips.
const urls = ['https://laputa-1257579200.cos.ap-guangzhou.myqcloud.com/stream-01.mov','https://laputa-1257579200.cos.ap-guangzhou.myqcloud.com/stream-02.mov','https://laputa-1257579200.cos.ap-guangzhou.myqcloud.com/stream-03.mov',];const requests = urls.map(url => fetch(url));
const responses = await Promise.all(requests);// Obtain the readable streams of the video clips.
const readableVideos = responses.map(res => res.body);
const { readable, writable } = new TransformStream();// Merge the video clips.
combine(readableVideos, writable);return new Response(readable, {headers: {'content-type': 'video/mp4',}});}
addEventListener('fetch', event => {event.respondWith(handleRequest(event.request));});Sample Preview
In the address bar of the browser, enter a URL that matches a trigger rule of the edge function to preview the merged
video. View the response header and verify that the video is transferred in chunked mode.

©2013-2022 Tencent Cloud. All rights reserved.

Page 311 of 360

Tencent Cloud EdgeOne

References
Runtime APIs: TransformStream
Runtime APIs: Response©2013-2022 Tencent Cloud. All rights reserved.

Page 312 of 360

Tencent Cloud EdgeOne

Protecting Data from Tampering：

Last updated 2024-01-25 11:32:07
In this example, an SHA-256 signature is calculated for a request body and compared with the signature that is
generated by the origin server. If the signatures are the same, the response content is not tampered with. Otherwise, a
416 status code is returned, indicating that the response content is tampered with. This example demonstrates how to
use an edge function to verify whether the response content sent from the origin server is tampered with.
Note:
Make sure that the origin server uses the same signature algorithm and tamper-proofing rules that are used in thisexample.
To use the tamper-proofing rules described in this example in the production environment, perform sorting on thecalculated signature to prevent the signature from being cracked by attackers.

Sample Code©2013-2022 Tencent Cloud. All rights reserved.

Page 313 of 360

Tencent Cloud EdgeOne// The supported text file formats.
const textFileTypes = ['application/javascript','text/html; charset=utf-8','text/css; charset=utf-8','text/xml; charset=utf-8'];// The supported image file format.
const imageFileTypes = ['image/jpeg'©2013-2022 Tencent Cloud. All rights reserved.

Page 314 of 360

Tencent Cloud EdgeOne];
function uint8ArrayToHex(arr) {return Array.prototype.map.call(arr, (x) => (('0' + x.toString(16)).slice(-2))).join('');}/*** The following algorithms are supported: MD5, SHA-1, SHA-256, SHA-384, and SHA-51* Note: When you calculate a signature on the origin server, do not directly sign
* Use the same method in the sample code to calculate the signature for comparison**/
async function checkAndResponse(response, hash, algorithm) {const headers = response.headers;let checkHash = 'sorry! not match';
let data = null;
const contentType = headers.get('Content-Type');if (textFileTypes.includes(contentType) || imageFileTypes.includes(contentType))
data = await response.arrayBuffer();}
let ret = await crypto.subtle.digest({name: algorithm}, data);
checkHash = uint8ArrayToHex(new Uint8Array(ret));headers.append(`X-Content-${algorithm}-Check`, checkHash);// Compare the signature that is calculated in real time with the signature thatif (checkHash !== hash) {return new Response(null, {headers,
status: 416});}
return new Response(data, {headers,
status: 200});}
async function handleEvent(event) {// Obtain the content that is returned by the origin server. If the content is ca
const response = await fetch(event.request);
if (response.status === 200) {const headers = response.headers;// The signature header of the content that is returned by the origin server.
const hash = headers.get('X-Content-Sha256');©2013-2022 Tencent Cloud. All rights reserved.

Page 315 of 360

Tencent Cloud EdgeOne

if (hash) {// Check whether the calculated signature is the same as the signature that ireturn checkAndResponse(response, hash, 'Sha-256');}}
return response;}
addEventListener('fetch', event => {event.respondWith(handleEvent(event));});

Sample Preview
In the address bar of the browser, enter a URL that matches a trigger rule of the edge function to preview the effect of
the sample code.
The signature that is calculated by the edge function is the same as the signature that is provided by the origin server.

The signature that is calculated by the edge function is different from the signature that is provided by the origin
server, and a 416 status code is returned.

©2013-2022 Tencent Cloud. All rights reserved.

Page 316 of 360

Tencent Cloud EdgeOne

References
Runtime APIs: Fetch
Runtime APIs: Web Crypto
Runtime APIs: Headers
Runtime APIs: Response©2013-2022 Tencent Cloud. All rights reserved.

Page 317 of 360

Tencent Cloud EdgeOne

Rewriting a m3u8 File and Configuring
Authentication：

Last updated 2023-04-13 11:14:30
In this example, a .m3u8 file is rewritten to support TypeA authentication that controls access to .m3u8 files and .ts
segments. You can modify the code as needed to support other authentication methods.

Sample Code©2013-2022 Tencent Cloud. All rights reserved.

Page 318 of 360

Tencent Cloud EdgeOne// The private key for TypeA authentication. Specify the key as needed and make surconst PK = '0123456789';// The validity period of the key for encryption and verification, in seconds.
const TTL = 60;
const KEY_NAME = 'key';
const UID = 0;
const SUFFIX_LIST = ['.m3u8', '.ts'];
addEventListener('fetch', (event) => {event.respondWith(handleEvent(event));});©2013-2022 Tencent Cloud. All rights reserved.

Page 319 of 360

Tencent Cloud EdgeOne

async function handleEvent(event) {try {const { request } = event;const urlInfo = new URL(request.url);
const suffix = getSuffix(urlInfo.pathname);// Check whether the file extension is .m3u8 or .ts.
if (!SUFFIX_LIST.includes(suffix)) {return fetch(request);}// TypeA authentication.
const checkResult = await checkTypeA(urlInfo);
if (!checkResult.flag) {return new Response(checkResult.message, {status: 403,
headers: {'X-Auth-Err': checkResult.message},});}// Rewrite the .m3u8 file and respond.
if (suffix === '.m3u8') {return fetchM3u8({
request,querySign: {basePath: urlInfo.pathname.substring(0, urlInfo.pathname.lastIndexOf('/')...checkResult.querySign,}});}// Respond with .ts resources.
if (suffix === '.ts') {return fetchTs(request);}} catch (error) {return new Response(error.stack, { status: 544 });}return fetch(request);}
async function checkTypeA(urlInfo) {const sign = urlInfo.searchParams.get(KEY_NAME) || '';©2013-2022 Tencent Cloud. All rights reserved.

Page 320 of 360

Tencent Cloud EdgeOne

const elements = sign.split('-');
if (elements.length !== 4) {return {flag: false,message: 'Invalid Sign Format',};}const [ts, rand, uid, md5hash] = elements;
if (ts === undefined || rand === undefined || uid === undefined || md5hash === unreturn {flag: false,message: 'Invalid Sign Format',};}if (!isNumber(ts)) {return {flag: false,message: 'Sign Expired',};}
if (Date.now() > (Number(ts) + TTL) * 1000) {return {flag: false,message: 'Sign Expired',};}
const hash = await md5([urlInfo.pathname, ts, rand, uid, PK].join('-'));
if (hash !== md5hash) {return {flag: false,message: 'Verify Sign Failed',};}
return {flag: true,message: 'success',querySign: {
rand,
uid,
md5hash,ts,},©2013-2022 Tencent Cloud. All rights reserved.

Page 321 of 360

Tencent Cloud EdgeOne};}
async function fetchM3u8({ request, querySign }) {request.headers.delete('Accept-Encoding');let response = null;try {response = await fetch(request);
if (response.status !== 200) {return response;}} catch (error) {return new Response('', {status: 504,
headers: { 'X-Fetch-Err': 'Invalid Origin' }});}const content = await response.text();
const lines = content.split('\\n');const contentArr = await Promise.all(lines.map(line => rewriteLine({ line, querySign })));return new Response(contentArr.join('\\n'), response);}
async function fetchTs(request) {let response = null;try {response = await fetch(request);
if (response.status !== 200) {return response;}} catch (error) {return new Response('', {status: 504,
headers: { 'X-Fetch-Err': 'Invalid Origin' }});}return response;}
async function rewriteLine({ line, querySign }) {// Skip empty lines.
if (/^\\s*$/.test(line)) {©2013-2022 Tencent Cloud. All rights reserved.

Page 322 of 360

Tencent Cloud EdgeOne

return line;}
if (line.charAt(0) === '#') {// Process #EXT-X-MAP.
if (line.startsWith('#EXT-X-MAP')) {const key = await createSign(querySign, line);line = line.replace(/URI="([^"]+)"/, (matched, p1) => {return p1 ? matched.replace(p1, `${p1}?key=${key}`) : matched;});}return line;}
const key = await createSign(querySign, line);
return `${line}?${KEY_NAME}=${key}`;}
async function createSign(querySign, line) {const { ts, rand, uid = 0 } = querySign;
const pathname = `${querySign.basePath}/${line}`;const md5hash = await md5([pathname, ts, rand, uid, PK].join('-'));
const key = [ts, rand, uid, md5hash].join('-');
return key;}function getSuffix(pathname) {const suffix = pathname.match(/\\.m3u8|\\.ts$/);return suffix ? suffix[0] : null;}function isNumber(num) {return Number.isInteger(Number(num));}function bufferToHex(arr) {return Array.prototype.map.call(arr, (x) => (x >= 16 ? x.toString(16) : '0' + x.toString(16))).join('');}
async function md5(text) {const buffer = await crypto.subtle.digest('MD5', TextEncoder().encode(text));
return bufferToHex(new Uint8Array(buffer));©2013-2022 Tencent Cloud. All rights reserved.

Page 323 of 360

Tencent Cloud EdgeOne}

Sample Preview
In the address bar of the browser, enter a URL that matches a trigger rule of the edge function to preview the effect of
the sample code. Sample URL:

如：http://www.example.com/index.m3u8?key=1678873033-123456-0-

32f4xxxxcabcxxxx1602xxxx6756d8f4.

References
Runtime APIs: Fetch
Runtime APIs: Web Crypto
Runtime APIs: Response
TypeA©2013-2022 Tencent Cloud. All rights reserved.

Page 324 of 360

Tencent Cloud EdgeOne

Adaptive Image Resize：

Last updated 2023-07-06 17:20:26
In this document, we demonstrate how to identify the client type via User-Agent in the request header, use fetch
API to get the image from the origin, and convert it to the format required by the browser.

©2013-2022 Tencent Cloud. All rights reserved.

Page 325 of 360

Tencent Cloud EdgeOne

addEventListener('fetch', event => {// If the function code throws an unhandled exception, Edge Functions forwards thevent.passThroughOnException();event.respondWith(handleEvent(event));});
async function handleEvent(event) {const { request } = event;const urlInfo = new URL(request.url);
const userAgent = request.headers.get('user-agent');©2013-2022 Tencent Cloud. All rights reserved.

Page 326 of 360

Tencent Cloud EdgeOne// Request a non-image resource
if (!/\\.(jpe?g|png)$/.test(urlInfo.pathname)) {return fetch(request);}// Image width on the mobile device
let width = 480;
const isPcClient = isPc(userAgent);// Image width on the PC
if (isPcClient) {width = 1280;}// Scale the image
const response = await fetch(request, {eo: {image: {width,}}});// Set the response header
response.headers.set('x-ef-client', isPcClient ? 'pc' : 'mobile');return response;}// Identify the request client typefunction isPc(userAgent) {const regex = /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMo
if(regex.test(userAgent)) {return false;}
return true;}

Sample Preview
In the address bar of the browser, enter a URL (such as https://example.com/images-resize/ef1.jpeg ) that matches a trigger rule of the edge function to preview the effect of the sample code.

©2013-2022 Tencent Cloud. All rights reserved.

Page 327 of 360

Tencent Cloud EdgeOne

For displaying on PC, scale the image to 1280 x 720.

For displaying on mobile devices, scale the image to 480 x 270.

©2013-2022 Tencent Cloud. All rights reserved.

Page 328 of 360

Tencent Cloud EdgeOne

References
Runtime APIs: Fetch
Runtime APIs: Headers
Runtime APIs: Response
Runtime APIs: Request©2013-2022 Tencent Cloud. All rights reserved.

Page 329 of 360

Tencent Cloud EdgeOne

Image Adaptive WebP：

Last updated 2023-10-30 17:41:37
This example determines whether the request header Accept contains image/webp . If so, the Edge function
will automatically convert the image format to WebP and cache it on the EdgeOne edge node. If your Web
application displays a large amount of PNG and JPEG format images and you want to automatically optimize theimages at the edge to reduce traffic bandwidth costs, you can use Edge functions to implement a smooth upgrade,
automatically converting PNG and JPEG format images to WebP format with 0 changes to the business code.
For more image conversion formats, please refer to ImageProperties.

©2013-2022 Tencent Cloud. All rights reserved.

Page 330 of 360

Tencent Cloud EdgeOne

async function handleEvent(event) {const { request } = event;// Get the image type supported by the client
const accept = request.headers.get('Accept');
const option = { eo: { image: {} } };// Check whether the client supports WebP format images, if not, respond with thif (accept && accept.includes('image/webp')) {option.eo.image.format = 'webp';}©2013-2022 Tencent Cloud. All rights reserved.

Page 331 of 360

Tencent Cloud EdgeOne

const response = await fetch(request, option);
return response;}
addEventListener('fetch', event => {// When the function code throws an unhandled exception, the Edge function transevent.passThroughOnException();event.respondWith(handleEvent(event));});

Example Preview
Enter the URL that matches the triggering rules of the Edge function in the address bar of the browser on the PC sideand mobile side (e.g., https://example.com/images-format/ef-1.jpeg ), and the image will be
automatically converted to Webp format.

Related References©2013-2022 Tencent Cloud. All rights reserved.

Page 332 of 360

Tencent Cloud EdgeOne

Runtime APIs: Fetch﻿
Runtime APIs: Headers﻿
Runtime APIs: Request﻿
Runtime APIs: FetchEvent﻿©2013-2022 Tencent Cloud. All rights reserved.

Page 333 of 360

Tencent Cloud EdgeOne

Customize Referer restriction rules：

Last updated 2024-07-16 16:35:32
Referer anti-leeching technology is a strategy adopted by websites to protect their resources and prevent otherwebsites from illegally using their content. This example determines the request sources by checking theRefererfield in the HTTP request header. You can flexibly customize the matching rules for this Referer . If theReferer does not exist or does not match the allowed domain list, the Edge functions will reject the request andreturn a 403 status code.

©2013-2022 Tencent Cloud. All rights reserved.

Page 334 of 360

Tencent Cloud EdgeOne

async function handleRequest(request) {// Collect the Referer
const referer = request.headers.get('Referer');// If the Referer is empty, access is denied
if (!referer) {return new Response(null, { status: 403 });}const urlInfo = new URL(request.url);
const refererRegExp = new RegExp(`^https?:\\/\\/${urlInfo.hostname}\\/t-[0-9a-z]{// If the Referer is not on the allowlist, access is denied
if (!refererRegExp.test(referer)) {return new Response(null, { status: 403 });}// Normal request, access EdgeOne node cache or origin-pull
return fetch(request);}
addEventListener('fetch', event => {// When the function code throws an unhandled exception, the Edge function transm
event.passThroughOnException();event.respondWith(handleRequest(event.request));});Example Preview
Enter the URL that matches the Edge function triggering rules in the address bar of the browser on the PC end andmobile end (e.g., https://example.com/images/ef-1.jpeg ) to preview the example effect.
HTTP request header Referer is https://example.com/t-0123456789/page, and the Edge function responds
normally to the image.

©2013-2022 Tencent Cloud. All rights reserved.

Page 335 of 360

Tencent Cloud EdgeOne

HTTP request header Referer is not on the allowlist, and the Edge function identifies it as a leeching link andresponds with a 403 status code.

©2013-2022 Tencent Cloud. All rights reserved.

Page 336 of 360

Tencent Cloud EdgeOne

Related References
Runtime APIs: Fetch﻿
Runtime APIs: Headers﻿
Runtime APIs: Response﻿©2013-2022 Tencent Cloud. All rights reserved.

Page 337 of 360

Tencent Cloud EdgeOne

Remote Authentication：

Last updated 2023-10-30 17:46:16
In order to avoid customers' resources being accessed by illegal users, this example transmits the request to thecustomer-specified remote authentication server. The authentication server verifies the user's request, and the Edge
functions decide whether to allow access to the target resources based on the check result returned by the remoteauthentication server. If the authentication fails, the client will be responded with a 403 status code.

async function handleRequest(request) {©2013-2022 Tencent Cloud. All rights reserved.

Page 338 of 360

Tencent Cloud EdgeOne// Remote authentication API address
const checkAuthUrl = 'https://www.example.com/';// Initiate remote authentication
const checkAuthRes = await fetch(checkAuthUrl);// Authentication passed, normal access to resources
if (checkAuthRes.status === 200) {return fetch(request, {headers: request.headers,});}// Authentication failed, prohibit access to resources
return new Response(null, {status: 403});}
addEventListener('fetch', e => {e.respondWith(handleRequest(e.request));});Example preview
Enter the URL that matches the triggering rules of the Edge functions in the address bar of the browser on both PC
and mobile (e.g., https://example.com/app/index.html ) to preview the example effect.
Authentication passed, normal access to resources.

©2013-2022 Tencent Cloud. All rights reserved.

Page 339 of 360

Tencent Cloud EdgeOne

Authentication failed, prohibit access to resources.

©2013-2022 Tencent Cloud. All rights reserved.

Page 340 of 360

Tencent Cloud EdgeOne

Related references
Runtime APIs: Fetch﻿
Runtime APIs: Response﻿©2013-2022 Tencent Cloud. All rights reserved.

Page 341 of 360

Tencent Cloud EdgeOne

HMAC Digital Signature：

Last updated 2023-12-13 10:54:00
Hash-based Message Authentication Code (HMAC) is a kind of message authentication code based on hash function,
mainly used to verify data integrity and identity authentication. Web Crypto API is used in this example toachieve HMAC-SHA256 signature and store the signature information in a request header. It achieves data integrity or
identity authentication collaborating with origin server. Developers can modify the code based on their specific needs.
Note
Cooperation with the origin server is required in this example, which means that the origin server must possess thecorresponding signature verification algorithm.
For live network use of the code provided in this example, modification must be made in accordance with thecomments.

Sample code

©2013-2022 Tencent Cloud. All rights reserved.

Page 342 of 360

Tencent Cloud EdgeOne

function uint8ArrayToHex(uint8Array) {return Array.prototype.map.call(uint8Array, x => ('0' + x.toString(16)).slice(-2)}
async function generateHmac({ secretKey, message, hash }) {const encoder = new TextEncoder();
const secretKeyBytes = encoder.encode(secretKey);
const messageBytes = encoder.encode(message);const key = await crypto.subtle.importKey('raw', secretKeyBytes, { name: 'HMAC',©2013-2022 Tencent Cloud. All rights reserved.

Page 343 of 360

Tencent Cloud EdgeOne

const signature = await crypto.subtle.sign('HMAC', key, messageBytes);
const signatureArray = new Uint8Array(signature);
return uint8ArrayToHex(signatureArray);}async function handleRequest(request) {const secretKey = 'YOUR_SECRET_KEY';// Please modify the message to the information that needs to be signed, generall
const message = 'YOUR_MESSAGE';// Choose one from SHA-1, SHA-256, SHA-384, and SHA-512 for hash.
const hmac = await generateHmac({ secretKey, message, hash: 'SHA-256' });request.headers.set('Authorization', `HMAC-SHA256 ${hmac}`);return fetch(request);}
addEventListener('fetch', event => {event.passThroughOnException();event.respondWith(handleRequest(event.request));});Sample Preview
Enter a URL (such as https://example.com/hmac ) that matches the trigger rule of edge function in theaddress bar of a browser on both the PC and mobile terminal to preview the example effect.
Identity verification failed.

©2013-2022 Tencent Cloud. All rights reserved.

Page 344 of 360

Tencent Cloud EdgeOne

Identity verification succeeded.

Related References
Runtime APIs: Fetch﻿
Runtime APIs: Web Crypto
Runtime APIs: Headers﻿
Runtime APIs: Response﻿©2013-2022 Tencent Cloud. All rights reserved.

Page 345 of 360

Tencent Cloud EdgeOne

Naming a Downloaded File：

Last updated 2023-12-13 10:55:46
In this example, the modification of the Content-Disposition in the response headers achieves the modification of thedownloaded file name according to the

fileName parameter in the request URL.

addEventListener('fetch', event => {event.passThroughOnException();event.respondWith(handleRequest(event.request));©2013-2022 Tencent Cloud. All rights reserved.

Page 346 of 360

Tencent Cloud EdgeOne});
async function handleRequest(request) {const url = new URL(request.url);
const fileName = url.searchParams.get('fileName');const response = await fetch(request);// Evaluate the response status code and the search parameter
if (response.status !== 200 || !fileName) {return response;}// Modify the Content-Disposition response header
response.headers.append('Content-Disposition', `attachment; filename="${fileName}
return response;}

Sample Preview
Enter a URL (such as https://example.com/origin.exe?fileName=modified.exe ) that matches thetrigger rule of edge function in the address bar of the browser on both the PC and mobile terminal to preview theexample effect.

Related References
Runtime APIs: Fetch﻿
Runtime APIs: Response﻿©2013-2022 Tencent Cloud. All rights reserved.

Page 347 of 360

Tencent Cloud EdgeOne

Obtaining Client IP Address：

Last updated 2023-12-13 10:57:07
Since the front end cannot directly obtain the client IP address, it's often necessary to obtain the client IP address
through the server side or third-party services in multiple business scenarios. The client IP address is obtained in thisexample through client IP header EO-Client-IP activated in the rule engine, and assembled into data in the formof JSON to respond to the clients, which succeeds in obtaining client IP address by the use of edge function.

addEventListener('fetch', event => {©2013-2022 Tencent Cloud. All rights reserved.

Page 348 of 360

Tencent Cloud EdgeOne

event.respondWith(handleRequest(event.request));});function handleRequest(request) {// Obtain the client IP through the EO-Client-IP header
const ip = request.headers.get('EO-Client-IP') || '';// Respond with JSON data
return new Response(JSON.stringify({ ip }), {headers: { 'content-type': 'application/json' },});}Sample Preview
Firstly, activate the client IP switch of the domain name that needs to trigger the edge function and set the header
name as EO-Client-IP in the Rule Engine configuration.

Once the configuration is effective, enter a URL (such as https://example.com/ip ) which matches the trigger
rule of the edge function in the address bar of the browser on both the PC and mobile terminal to obtain the client's IP
address:

Related References
Runtime APIs: Fetch﻿
Runtime APIs: Response﻿©2013-2022 Tencent Cloud. All rights reserved.

Page 349 of 360

Tencent Cloud EdgeOne

Best Practices
Adaptive Image Format Conversion via Edge
Functions：

Last updated 2023-07-10 09:48:54
This document describes how to the convert image format by using edge functions without changing the original client
request URL. Edge functions can automatically convert the image according to the User-Agent header in theclient request.

BackgroundFor sites providing lots of images, adapting the image for different browser is a must. At the same time, they need tothe compress the images without losing quality, so as to reduce the cost on data transfer. For example, they need to:
Return webp images for Chrome, Opera, Firefox and Edge browsers.
Return jp2 images for the Safari browser.
Return jxr images for the IE browser.
Return webp images for all the other browsers.
Edge functions can automatically convert the image according to the User-Agent header in the client request. If
you want to proactively convert the image format in the request URL, you can also use the image processing feature.

Use Cases
example.com is connected to EdgeOne, with all the images stored under
http://image.example.com/image/ . You need to automatically convert all image files under this directory
according to the browser type of the client. https://image.example.com/image/test.jpg is taken as thetest image.

©2013-2022 Tencent Cloud. All rights reserved.

Page 350 of 360

Tencent Cloud EdgeOne

Directions
1. Log in to the EdgeOne console and click the target site in the site list to display second-level menus for sitemanagement.
2. In the left sidebar, click Edge Functions > Function Management.
3. On the Function management page, click Create function.
4. On the function creation page, enter the function name, description and codes. See below for the sample codes:©2013-2022 Tencent Cloud. All rights reserved.

Page 351 of 360

Tencent Cloud EdgeOne// Browser image format
const broswerFormat = {Chrome: 'webp',
Opera: 'webp',
Firefox: 'webp',
Safari: 'jp2',
Edge: 'webp',
IE: 'jxr'};
addEventListener('fetch', event => {©2013-2022 Tencent Cloud. All rights reserved.

Page 352 of 360

Tencent Cloud EdgeOne// If the function code throws an unhandled exception, Edge Functions forwards thevent.passThroughOnException();event.respondWith(handleEvent(event));});
async function handleEvent(event) {const { request } = event;const userAgent = request.headers.get('user-agent');
const bs = getBroswer(userAgent);
const format = broswerFormat[bs];// Do not convert the image format
if (!format) {return fetch(request);}// Convert image format
const response = await fetch(request, {eo: {image: {format}}});// Set the response header
response.headers.set('x-ef-format', format);return response;}
function getBroswer(userAgent) {if (/Edg/i.test(userAgent)) {return 'Edge'}
if (/Trident/i.test(userAgent)) {return 'IE'}
if (/Firefox/i.test(userAgent)) {return 'Firefox';}
if (/Chrome/i.test(userAgent)) {return 'Chrome';}
if (/Opera|OPR/i.test(userAgent)) {return 'Opera';}©2013-2022 Tencent Cloud. All rights reserved.

Page 353 of 360

Tencent Cloud EdgeOne

if (/Safari/i.test(userAgent)) {return 'Safari'}}
5. Click Create and deploy function. Wait till the deployment completed. Click Add trigger rule.

6. Configure the condition to trigger this function. In this case, you can configure two conditions, which are combinedwith AND.
When the request HOST equals to Image.example.com .
When the request URL Path equals to /image/* .
When both the conditions are met, the edge function is triggered to process the image automatically.

7. Click Save.
8. You can verify the functions in two ways:
Using curl to test
Browser Access Test
You can run a curl command with the specified User-Agent to test.
ChromeSafari©2013-2022 Tencent Cloud. All rights reserved.

Page 354 of 360

Tencent Cloud EdgeOne

IE
To test on Chrome browser on Mac/Linux OS, run the following command on the device: curl --user-agent"chrome" https://image.example.com/image/test.jpg -i
Check if Content-Type in the response is image/webp .

On Mac/Linux OS, run the following command on the device: curl --user-agent "safari"https://image.example.com/image/test.jpg -i
Check if Content-Type in the response is image/jp2 .

©2013-2022 Tencent Cloud. All rights reserved.

Page 355 of 360

Tencent Cloud EdgeOne

On Mac/Linux OS, run the following command on the device: curl --user-agent "Trident"
https://image.example.com/image/test.jpg -i
Check if Content-Type in the response is image/vnd.ms-photo .

Access the test image address https://image.example.com/image/test.jpg with different browsers.
Check the format for image returned to see whether the edge function works properly.
ChromeSafari
IE©2013-2022 Tencent Cloud. All rights reserved.

Page 356 of 360

Tencent Cloud EdgeOne

Access the test image address https://image.example.com/image/test.jpg wit Chrome browser. The
responded image should be in webp format.

Access the test image address https://image.example.com/image/test.jpg with Safari browser. The
responded image should be in jp2 format.

©2013-2022 Tencent Cloud. All rights reserved.

Page 357 of 360

Tencent Cloud EdgeOne

Access the test image address https://image.example.com/image/test.jpg with IE browser. The
responded image should be in jxr format.

©2013-2022 Tencent Cloud. All rights reserved.

Page 358 of 360

Tencent Cloud EdgeOne

Relevant Documentation©2013-2022 Tencent Cloud. All rights reserved.

Page 359 of 360

Tencent Cloud EdgeOne

Sample function: Image auto-adaptation﻿
Resizing and Converting Images©2013-2022 Tencent Cloud. All rights reserved.

Page 360 of 360