An HTTP trigger invokes a function through HTTP requests. This trigger is ideal for rapidly building web services. Before you use it, review the limits on triggers and HTTP(S), synchronous and asynchronous invocation methods, and authentication, authorization, and cross-origin resource sharing (CORS) configuration. This topic covers these subjects and common questions.
Usage notes
Security risk of anonymous triggers: If you set the Authentication Method to No Authentication, no identity verification is performed. Anyone can invoke your function via HTTP requests. This poses a risk of URL leakage. To mitigate this risk, you can validate the
Authorizationheader in your application code. For more information, see Configure signature authentication for HTTP triggers.APK download restriction: Per national cybersecurity regulations, starting June 10, 2024, newly created HTTP triggers cannot download Android Package Kit (APK) files (MIME type:
application/vnd.android.package-archive) from public endpoints. Requests return status code 400. For more information, see Why does a public endpoint of an HTTP trigger fail to return an .apk file?.VIP rotation: Function Compute rotates virtual IP addresses (VIPs) to improve system resilience and service stability. The VIPs associated with public and internal endpoints of HTTP triggers rotate periodically. Hard-coding VIPs may cause service interruptions. Use custom domain names to ensure business stability. Failures caused by improper VIP usage are not covered by Function Compute compensation.
You can access Function Compute using a custom domain name with a CNAME. For more information, see Configure a custom domain name.
Limits
Limits on triggers
You can create only one HTTP trigger per function version or alias. For more information, see Manage versions and Manage aliases.
Built-in domain names are for testing only. Do not use them for external production services because their stability is not guaranteed.
NoteTo provide website services externally, use an ICP-filed custom domain name. Bind the domain to your function and serve traffic through that domain. For more information, see Configure a custom domain name.
Limits on HTTP(S)
You can use GET, POST, PUT, DELETE, HEAD, PATCH, and OPTIONS methods to trigger functions. These methods suit simple request-response scenarios. For more information, see Configure an HTTP trigger.
Limits on HTTP requests
Request headers do not support custom fields that start with x-fc- or the following fields:
connection
keep-alive
The system returns status code
400and error codeInvalidArgumentif a request exceeds any of the following limits:Headers size: The total size of all keys and values in headers cannot exceed 8 KB.
Path size: The total size of a path, including all query parameters, cannot exceed 4 KB.
Body size: The total body size of a synchronous invocation request cannot exceed 32 MB. For more information about the body size limit of asynchronous invocation requests, see Function execution resource limits.
Limits on HTTP responses
Response headers do not support custom fields that start with x-fc- or the following fields:
connection
content-length
date
keep-alive
server
upgrade
content-disposition:attachment
NoteFor security reasons, if you use the default aliyuncs.com domain name of Function Compute, the server adds the content-disposition: attachment header to response headers, which causes the browser to download the returned results as attachments. To remove this restriction, use a custom domain name. For more information, see Configure a custom domain name.
The system returns status code
502and error codeBadResponseif a response exceeds any of the following limits:Headers size: The total size of all keys and values in headers cannot exceed 8 KB.
Comparison with API Gateway and benefits
You can use either HTTP triggers or API Gateway triggers to build web applications. Here is how each works:
HTTP triggers: Bind a custom domain name to map different HTTP paths to different functions. For more information, see Configure a custom domain name.
API Gateway triggers: Use API Gateway with Function Compute as the backend service to achieve similar functionality. For more information, see Use Function Compute as an API backend service.
Compared with API Gateway triggers, HTTP triggers offer the following benefits:
Reduce developer learning time and simplify debugging. Help developers quickly build web applications and APIs using Function Compute.
Reduce request processing steps. HTTP triggers support efficient request and response formats. You do not need to encode or decode requests to JSON format. This improves performance.
Use familiar HTTP test tools to verify the features and performance of Function Compute.
Easily integrate with other webhook-enabled services such as CDN origin fetch and Simple Message Queue (formerly MNS).
Invocation methods
Synchronous invocation
In a synchronous invocation, the function processes the event and returns the result immediately. HTTP triggers use synchronous invocation by default. For more information, see Synchronous calls.
Asynchronous invocation
In an asynchronous invocation, Function Compute persists the request and returns a response immediately without waiting for execution to complete.
Asynchronous invocation: Add the
"X-Fc-Invocation-Type":"Async"request header to invoke a function asynchronously at the request level.Asynchronous tasks: After enabling asynchronous tasks for an HTTP function, add the
"X-Fc-Async-Task-Id":"g6u*****iyvhd3jk8s6bhj0hh"request header to configure the invocation ID for the asynchronous task.
For more information about request headers, see Invoke a function.
After a successful asynchronous invocation, Function Compute returns status code 202. This indicates the request was received successfully. It also returns the request ID in the response header. The format is "X-Fc-Request-Id": "80bf7****281713e1".
If Function Compute returns any status code other than 202, the invocation failed. For more information about causes of failures, see Configure a retry mechanism.
References
For more information about asynchronous invocations, see Asynchronous invocations.
For more information about asynchronous tasks, see Asynchronous tasks.
Authentication and authorization
You can configure authentication and authorization for HTTP triggers. External users must pass authentication and authorization before Function Compute processes their requests. Supported authentication and authorization methods include the following:
CORS request processing
By default, Function Compute allows cross-origin function invocations. It also lets you write custom code to handle cross-origin resource sharing (CORS) requests.
Simple requests
A preflight request is not required for simple requests. You can set headers that start with Access-Control-Allow-* in your function code to implement basic access control. For simple requests, Function Compute supports the following custom headers: Access-Control-Allow-Origin, Access-Control-Allow-Headers, and Access-Control-Max-Age.
If you do not configure custom headers, Function Compute sets the following response headers by default:
Access-Control-Allow-Origin: the Origin header of the request.Access-Control-Allow-Credentials: the default value istrue.Access-Control-Expose-Headers: custom headers defined by Function Compute.
Non-simple requests
A non-simple request sends a preflight request before the actual request. A browser sends a preflight request using the OPTIONS method, then sends the actual request to invoke the function. Rules for non-simple requests match those for simple requests. To customize the preflight response, add the OPTIONS method to your HTTP trigger and process the OPTIONS request in your function code. Specifically, set headers that start with Access-Control-Allow-* to control cross-origin behavior.
For preflight requests, Function Compute supports the following custom headers: Access-Control-Allow-Origin, Access-Control-Allow-Headers, Access-Control-Allow-Methods, and Access-Control-Max-Age.
This example shows how to process preflight requests in function code using the built-in Node.js runtime:
exports.handler = (event, context,callback) => {
console.log('hello world');
const method = JSON.parse(event).requestContext.http.method;
if (method === 'OPTIONS') {
// Set response headers to handle the preflight request.
const fcResponse = {
'statusCode': 204,
'headers': {
'Access-Control-Allow-Origin': 'http://www.fc.com',
'Access-Control-Allow-Methods': 'POST',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
'Access-Control-Max-Age':'3600'
},
'body': 'hello world'
};
callback(null, fcResponse);
} else {
callback(null, {
'statusCode': 500,
'body': 'hello world'
});
}
};API Configured CORS
API Configured CORS is currently in invitational preview. To enable it, contact us and provide your Alibaba Cloud account ID (UID).
Feature overview
API Configured CORS is a gateway-layer capability provided by Function Compute (FC). Configure CORS policies directly on HTTP triggers or custom domain names. No CORS logic is needed in function code.
Key benefits
Simpler code: Decouple CORS logic from business logic. Focus only on business implementation.
Lower cost: The gateway responds to OPTIONS preflight requests directly. This avoids triggering function instances and saves duration costs.
Centralized management: Configure policies at the trigger or domain level for easier multi-service administration.
Faster responses: The gateway returns preflight results directly, reducing latency.
Applicability
API version: Available only for FC 3.0 functions (API version: 2023-03-30).
Access method: HTTP triggers (including built-in test domains) or bound custom domain names.
Configuration method
Configure using the Update trigger or Update custom domain name API.
CORS configuration parameters
Parameter name | Type | Description | Default value | Limitations/constraints |
allowOrigins | Array | List of origins allowed to access resources. | - | Maximum 100 items. Each item is up to 256 characters. Supports |
allowMethods | Array | List of allowed HTTP methods. | Trigger methods | Do not manually configure |
allowHeaders | Array | Custom request headers allowed to be sent by browsers. | - | Maximum 50 items. Supports |
exposeHeaders | Array | Response header fields allowed to be accessed by browsers. | System default value | Maximum 50 items. |
allowCredentials | Boolean | Whether to allow credentials (such as cookies) in cross-origin requests. | false | If set to |
maxAge | Integer | Cache duration (in seconds) for preflight (OPTIONS) responses. | 3600 | Valid range: 0 to 86400. |
Values for allowOrigins:
Wildcard
*: Allows all origins (only whenallowCredentialsisfalse).Wildcard
https://*: Allows all origins starting withhttps://.Specific domain: For example,
https://example.com.Multiple domains: As an array, for example,
["https://example.com", "https://app.example.com"].Subdomain wildcards (for example,
https://*.example.com) are not supported.
Values for allowMethods:
Standard HTTP methods:
GET,POST,PUT,DELETE,PATCH,HEAD.Wildcard
*: Allows all HTTP methods.Not supported
OPTIONS: The OPTIONS method is automatically handled by the system for preflight requests.
Request handling logic
After configuring API Configured CORS, the gateway processes requests based on type:
1. Preflight requests (OPTIONS)
When a browser sends a preflight request for a non-simple request, the gateway validates the Origin, Access-Control-Request-Method, and Access-Control-Request-Headers:
Validation passes: Return
204 No Contentand inject configured CORS response headers. Do not trigger the function.Validation fails:
Origin matches but other headers do not: The gateway sets basic CORS headers.
The origin does not match because CORS headers are not configured.
The request forwards to the function instance.
2. Simple requests (GET/POST/HEAD, etc.)
The gateway validates only the Origin:
Validation passes: Inject
Access-Control-Allow-Originand other CORS headers into the response. Forward the request to the function for execution.Validation fails: Do not inject CORS headers. Still forward the request to the function for execution.
Compatibility and precedence
Multiple CORS handling methods may apply to the same path. Precedence order (highest to lowest):
API Configured CORS: If configured, the gateway applies this logic first.
Default CORS: If API Configured CORS is disabled, the gateway uses built-in default CORS behavior.
Function-level CORS: Headers returned by the function merge with (append to) headers from the above methods. This ensures compatibility.
Comparison of approaches
Feature | API Configured CORS (recommended) | Default CORS | User-defined CORS (code) |
Are preflight requests billed? | Free of charge (gateway interception) | Potential charges | Billed (triggers function) |
Code intrusion | None | None | High |
Supported API versions | FC 3.0 only | All versions | All versions |
Configuration complexity | Low (one-time setup) | No configuration needed | High (requires OPTIONS method handling) |
FAQ
Q1: Why does my API call fail after I configure allowMethods to include OPTIONS?
A: By design, the OPTIONS method is managed automatically by the Function Compute gateway. Do not manually add OPTIONS to the corsConfig allowMethods array. The system handles all preflight requests automatically.
Q2: After successful configuration, why does my OPTIONS request still return 200 instead of 204?
A: Confirm whether your account has been granted invitational preview access by the on-duty team. If the interception plugin is not fully activated, the gateway falls back to default CORS logic (returns 200 and forwards to the function).
Q3: Can allowOrigins use subdomain wildcards (for example, *.example.com)?
A: Subdomain fuzzy matching is not supported. List all second-level domains explicitly in the allowOrigins array, or use https://* for broad matching.
Q4: If my function code also writes CORS headers, will conflicts occur?
A: No conflicts occur. Headers generated by the gateway merge with headers returned by the function. If duplicates exist, browsers typically use the first or standards-compliant value. This helps ensure smooth migration without service interruption.