Trigger functions using HTTP requests. This approach is ideal for quickly building web services and similar applications. Before you begin, review the following: usage limits for HTTP and HTTPS triggers; synchronous and asynchronous invocation methods; and how to configure authentication, authorization, and cross-origin resource sharing (CORS). This topic covers these topics and answers common questions.
Important Notes
-
Security risk of anonymous triggers: If you set the Authentication Method to No Authentication when configuring an HTTP trigger, no identity verification occurs. Anyone can invoke your function via HTTP requests, which increases the risk of URL exposure. To implement custom authorization, validate the
Authorizationrequest header in your application code. For details, see Configure signature-based authentication for HTTP triggers. -
APK download restriction: In compliance with national cybersecurity regulations, starting June 10, 2024, newly created HTTP triggers prohibit downloading APK files (MIME type
application/vnd.android.package-archive) over public network endpoints. Requests return HTTP status code 400. For details, see How to ensure your HTTP trigger's public endpoint returns .apk files correctly. -
VIP rotation: Function Compute rotates virtual IP addresses (VIPs) to improve system resilience and service stability. The VIPs associated with your HTTP trigger’s public or private endpoints change periodically. Hard-coding VIPs may cause service interruptions. Use a custom domain name to maintain stable business operations. Failures caused by improper VIP usage are not covered under Function Compute’s service-level agreement.
Use a custom domain name with CNAME configuration. For details, see Configure a custom domain name.
Limits
Trigger limits
-
You can create at most one HTTP trigger per version or alias. For more information, see Version management and Alias management.
-
Built-in domain names are for testing only. Do not use them for production-facing services because their stability is not guaranteed.
NoteTo host website-style services publicly, use an ICP-filed custom domain name. Bind the domain name to your function before exposing it. For more information, see Configure a custom domain name.
HTTP/HTTPS protocol limits
Function Compute supports triggering functions using GET, POST, PUT, DELETE, HEAD, PATCH, and OPTIONS requests. These are suitable for simple request-response scenarios. For more information, see Configure an HTTP trigger.
-
HTTP request limits
-
Custom request headers that start with x-fc- are not supported. The following custom headers are also unsupported:
-
connection
-
keep-alive
-
-
If a request exceeds any of the following limits, Function Compute returns HTTP status code
400and error codeInvalidArgument.-
Header size: The combined size of all header keys and values must not exceed 8 KB.
-
Path size: The total size of the path, including all query parameters, must not exceed 4 KB.
-
Body size: For synchronous invocations, the request body must not exceed 32 MB. For asynchronous invocations, refer to Function execution resource limits.
-
-
-
HTTP response limits
-
Custom response headers that start with x-fc- are not supported. The following custom headers are also unsupported:
-
connection
-
content-length
-
date
-
keep-alive
-
server
-
upgrade
-
content-disposition:attachment
NoteFor security, Function Compute adds content-disposition: attachment to response headers when you use the default Function Compute domain name (aliyuncs.com). This causes browsers to download responses as attachments. To remove this behavior, configure a custom domain name. For more information, see Configure a custom domain name.
-
-
If a response exceeds the following limit, Function Compute returns HTTP status code
502and error codeBadResponse.-
Header size: The combined size of all header keys and values must not exceed 8 KB.
-
-
Comparison with API Gateway
Both HTTP triggers and API Gateway triggers support building web applications. Use them as follows:
-
HTTP trigger: Map different HTTP paths to your HTTP function by binding a custom domain name. For details, see Configure a custom domain name.
-
API Gateway trigger: You can also use API Gateway with Function Compute as the backend service. For details, see Use Function Compute as an API backend service.
Compared to API Gateway triggers, HTTP triggers offer these advantages:
-
Reduce developer learning time and simplify debugging. Help developers build web applications and APIs with Function Compute faster.
-
Reduce request processing steps. HTTP triggers support efficient request and response formats without JSON encoding or decoding, delivering better performance.
-
Support familiar HTTP testing tools to verify Function Compute functionality and performance.
-
Easily integrate with other webhook-enabled services such as CDN origin fetch and Simple Message Queue (formerly MNS).
Invocation Methods
Synchronous invocation
In synchronous invocation, the function processes the event and returns the result immediately. HTTP triggers use synchronous invocation by default. For more information, see Synchronous invocation.
Asynchronous invocation
In asynchronous invocation, Function Compute persists the request and returns a response immediately, without waiting for the function to finish executing.
-
Asynchronous invocation: Add the request header
"X-Fc-Invocation-Type":"Async"to enable request-level asynchronous invocation. -
Asynchronous task: After configuring an asynchronous task for your HTTP function, add the request header
"X-Fc-Async-Task-Id":"g6u*****iyvhd3jk8s6bhj0hh"to specify the invocation ID.
For more information about request headers, see Invoke a function.
After a successful asynchronous invocation, Function Compute returns HTTP status code 202, indicating the request was accepted. It also returns the request ID in the response header, for example: "X-Fc-Request-Id": "80bf7****281713e1".
If Function Compute returns any status code other than 202, the invocation failed. For failure reasons, see Retry mechanism.
Related documentation:
-
For more information about asynchronous invocation, see Asynchronous invocation.
-
For more information about asynchronous tasks, see Asynchronous task.
Authentication and Authorization
Function Compute supports authentication and authorization for HTTP triggers. External users must pass Function Compute’s authentication and authorization checks before accessing your function through an HTTP trigger. Supported authentication methods include the following:
CORS Request Handling
By default, Function Compute allows cross-origin requests to your function. You can also customize how your function handles cross-origin (CORS) requests in your function code.
Simple requests
Simple requests do not send preflight requests, so you can directly set headers that start with Access-Control-Allow-* in your function code to implement simple 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 set custom headers, Function Compute sets the following response headers by default, based on the corresponding request headers:
-
Access-Control-Allow-Origin: The Origin header of the request. -
Access-Control-Allow-Credentials: Default value istrue. -
Access-Control-Expose-Headers: Headers defined by Function Compute.
Non-simple requests
Non-simple requests send a preflight request before the actual request. A non-simple request includes one OPTIONS method invocation and one actual function invocation. The rules for the actual request match those for simple requests. To customize the preflight response, add the OPTIONS method to your HTTP trigger and handle the OPTIONS request in your function code. Set response headers that start with Access-Control-Allow- to control cross-origin behavior.
For preflight requests, Function Compute supports these customizable headers: Access-Control-Allow-Origin, Access-Control-Allow-Headers, Access-Control-Allow-Methods, and Access-Control-Max-Age.
For example, here is how to handle preflight requests in Node.js runtime code:
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 preflight requests
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 available as an invitational preview. To enable it, contact us and provide your Alibaba Cloud account ID (UID).
Feature description
API Configured CORS is a gateway-layer capability provided by Function Compute (FC). Configure CORS policies directly on HTTP triggers or custom domain names without writing CORS logic in your function code.
Key benefits
-
Simpler code: Decouple CORS logic from business logic. Focus only on implementing your core business logic.
-
Lower cost: The gateway responds to OPTIONS preflight requests directly. No function instance is triggered, saving 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.
Applicable scope
-
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
Configure using the Update trigger or Update custom domain name API.
CORS configuration parameters
|
Parameter name |
Type |
Description |
Default value |
Limit or constraint |
|
allowOrigins |
Array |
List of origins allowed to access resources. |
- |
Maximum 100 items. Each item must not exceed 256 characters. Supports |
|
allowMethods |
Array |
List of allowed HTTP methods. |
Trigger methods |
Do not manually configure |
|
allowHeaders |
Array |
Custom request headers allowed from browsers. |
- |
Maximum 50 items. Supports |
|
exposeHeaders |
Array |
Response header fields allowed for browser access. |
System default |
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 enabling 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 headers:
-
Validation passes: Return HTTP status code
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.
-
Origin mismatch: The CORS header is not set.
-
The request forwards to the function instance.
-
2. Simple requests (GET, POST, HEAD, etc.)
The gateway validates only the Origin header:
-
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 priority
Multiple CORS handling methods may apply to the same path. Priority order (highest to lowest):
-
API Configured CORS: If enabled, the gateway applies this logic first.
-
Default CORS: If API Configured CORS is disabled, the gateway uses built-in default cross-origin echoing.
-
Function-defined CORS: Headers returned by your function merge (append) with the above results to ensure compatibility.
Comparison of approaches
|
Feature |
API Configured CORS (recommended) |
Default CORS |
User-defined CORS (code) |
|
Is preflight request billed? |
Not billed (gateway block) |
Potential charges |
Billed (function triggered) |
|
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 (must handle OPTIONS method) |
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 list. 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” permissions by the on-duty team. If the interception plug-in 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 required 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 your function. If duplicates exist, browsers typically use the first or standards-compliant value. This ensures existing applications remain uninterrupted during smooth migration.