HTTP Trigger Overview

更新时间:
复制 MD 格式

HTTP triggers let you invoke a Function Compute function through standard HTTP or HTTPS requests. They are the fastest path to building web services and APIs on Function Compute: no encoding overhead, no additional gateway to manage, and compatible with any HTTP testing tool or webhook-enabled service.

How it works

An HTTP trigger exposes your function as an HTTP endpoint. When a request arrives, Function Compute authenticates it (if configured), then passes the request to your function and returns the function's HTTP response to the caller.

Supported HTTP methods: GET, POST, PUT, DELETE, HEAD, PATCH, and OPTIONS.

A minimal web function handler in Node.js:

exports.handler = (event, context, callback) => {
  const request = JSON.parse(event);
  const response = {
    statusCode: 200,
    headers: { 'Content-Type': 'text/plain' },
    body: 'Hello from Function Compute'
  };
  callback(null, response);
};

The event object contains the full HTTP request (path, headers, body, method). Return an object with statusCode, headers, and body to send an HTTP response.

Usage notes

Before building with HTTP triggers, be aware of these behaviors.

Anonymous access risk

If you set Authentication Method to No Authentication, anyone with the endpoint URL can invoke your function. To enforce custom authorization, validate the Authorization header in your function code. For details, see Configure signature-based authentication for HTTP triggers.

Regulatory spot checks: In compliance with national cybersecurity regulations, Alibaba Cloud performs random spot checks on ICP-filed domains. Anonymous HTTP domains may be probed, and such probes generate invocation records.

APK download restriction

Starting June 10, 2024, newly created HTTP triggers block APK file downloads (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 periodically rotates the virtual IP addresses (VIPs) associated with public and private endpoints. Hard-coding VIPs causes service interruptions and is not covered under the Function Compute service-level agreement (SLA). Use a custom domain name with CNAME configuration for stable access. For details, see Configure a custom domain name.

Default domain and attachment behavior

When using the default aliyuncs.com domain, Function Compute adds content-disposition: attachment to all responses, causing browsers to download responses as files rather than render them. Configure a custom domain name to remove this behavior.

Limitations

Trigger limits

  • At most one HTTP trigger per function version or alias. See Version management and Alias management.

  • Built-in domain names are for testing only — stability is not guaranteed. Do not use them for production-facing services. For public-facing services, bind an ICP-filed custom domain name before exposing your function. See Configure a custom domain name.

Request limits

LimitValue
Header size (all keys + values)8 KB
Path size (including query parameters)4 KB
Body size — synchronous invocation32 MB
Body size — asynchronous invocationSee Function execution resource limits

Exceeding the header, path, or body limits for synchronous invocations returns HTTP status code 400 with error code InvalidArgument.

Unsupported request headers: any header starting with x-fc-, plus connection and keep-alive.

Response limits

LimitValue
Header size (all keys + values)8 KB

Exceeding the response header limit returns HTTP status code 502 with error code BadResponse.

Unsupported response headers: any header starting with x-fc-, plus connection, content-length, date, keep-alive, server, upgrade, and content-disposition:attachment.

Invocation methods

Synchronous invocation

HTTP triggers use synchronous invocation by default. The function processes the request and returns the result before the connection closes. See Synchronous invocation.

Asynchronous invocation

In asynchronous invocation, Function Compute persists the request and immediately returns HTTP status code 202, without waiting for the function to finish. Any status code other than 202 means the invocation failed. See Retry mechanism for failure handling.

Two ways to invoke asynchronously:

  • Request-level async: Add the header "X-Fc-Invocation-Type": "Async" to any HTTP request. See Asynchronous invocation.

  • Asynchronous task: After configuring an asynchronous task for your function, add the header "X-Fc-Async-Task-Id": "<task-id>" to specify the invocation ID. See Asynchronous task.

The response includes the request ID in the header, for example: "X-Fc-Request-Id": "80bf7****281713e1". For all supported request headers, see Invoke a function.

Authentication and authorization

External callers must pass Function Compute's authentication checks before accessing your function through an HTTP trigger. Supported methods:

Cross-origin resource sharing (CORS)

Function Compute supports three ways to handle cross-origin resource sharing (CORS) requests, with different tradeoffs in cost, complexity, and flexibility.

FeatureAPI Configured CORS (recommended)Default CORSUser-defined CORS (code)
Preflight request billed?Not billed (gateway handles it)Potential chargesBilled (function triggered)
Code changes requiredNoneNoneHigh
Supported API versionsFC 3.0 onlyAll versionsAll versions
Configuration complexityLow (one-time setup)NoneHigh (must handle OPTIONS)

Default CORS behavior

By default, Function Compute echoes back CORS headers based on the request. For simple requests (no preflight), the response includes:

  • Access-Control-Allow-Origin: copied from the request Origin header

  • Access-Control-Allow-Credentials: true

  • Access-Control-Expose-Headers: headers defined by Function Compute

Handle CORS in function code

For simple requests, set Access-Control-Allow-* headers directly in your response.

For non-simple requests, a browser sends a preflight OPTIONS request before the actual request. Add OPTIONS to your HTTP trigger's allowed methods and handle it in your function code.

<details> <summary>Node.js example</summary>

exports.handler = (event, context, callback) => {
  const method = JSON.parse(event).requestContext.http.method;
  if (method === 'OPTIONS') {
    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: ''
    };
    callback(null, fcResponse);
  } else {
    callback(null, {
      statusCode: 200,
      body: 'hello world'
    });
  }
};

</details>

<details> <summary>Python example</summary>

import json

def handler(event, context):
    evt = json.loads(event)
    method = evt.get('requestContext', {}).get('http', {}).get('method', '')
    if method == 'OPTIONS':
        return {
            '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': ''
        }
    return {
        'statusCode': 200,
        'body': 'hello world'
    }

</details>

<details> <summary>Go example</summary>

package main

import (
    "context"
    "encoding/json"
)

type HttpRequest struct {
    RequestContext struct {
        Http struct {
            Method string `json:"method"`
        } `json:"http"`
    } `json:"requestContext"`
}

type HttpResponse struct {
    StatusCode int               `json:"statusCode"`
    Headers    map[string]string `json:"headers"`
    Body       string            `json:"body"`
}

func Handler(ctx context.Context, event []byte) (*HttpResponse, error) {
    var req HttpRequest
    if err := json.Unmarshal(event, &req); err != nil {
        return nil, err
    }
    if req.RequestContext.Http.Method == "OPTIONS" {
        return &HttpResponse{
            StatusCode: 204,
            Headers: map[string]string{
                "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: "",
        }, nil
    }
    return &HttpResponse{StatusCode: 200, Body: "hello world"}, nil
}

</details>

API Configured CORS

API Configured CORS is available as an invitational preview. To enable it, contact us and provide your Alibaba Cloud account ID (UID).

API Configured CORS is a gateway-layer feature. Configure CORS policies directly on an HTTP trigger or custom domain name — no CORS logic needed in your function code.

Key benefits:

  • No code changes: Decouple CORS handling from business logic.

  • Lower cost: The gateway handles preflight OPTIONS requests directly, so no function instance runs.

  • Centralized management: Apply CORS policies at the trigger or domain level.

  • Lower latency: The gateway returns preflight responses without invoking your function.

Scope:

  • FC 3.0 functions only (API version 2023-03-30)

  • Applies to HTTP triggers (including built-in test domains) and bound custom domain names

Configure using the Update trigger or Update custom domain name API.

CORS configuration parameters

ParameterTypeDescriptionDefaultConstraint
allowOriginsArrayOrigins allowed to access resourcesMax 100 items, each ≤ 256 characters. Supports * or https://*.
allowMethodsArrayAllowed HTTP methodsTrigger methodsDo not include OPTIONS — the gateway handles preflight automatically.
allowHeadersArrayCustom request headers allowed from browsersMax 50 items. Supports *.
exposeHeadersArrayResponse headers exposed to browsersSystem defaultMax 50 items.
allowCredentialsBooleanWhether to allow cookies and credentials in cross-origin requestsfalseIf true, allowOrigins cannot be *.
maxAgeIntegerCache duration for preflight responses, in seconds3600Range: 0–86400.

Values for `allowOrigins`:

  • *: Allow all origins (only when allowCredentials is false).

  • https://*: Allow all origins starting with https://.

  • Specific domain: https://example.com.

  • Multiple domains: ["https://example.com", "https://app.example.com"].

  • Subdomain wildcards (for example, https://*.example.com) are not supported. List all domains explicitly.

Values for `allowMethods`:

  • Standard HTTP methods: GET, POST, PUT, DELETE, PATCH, HEAD.

  • *: Allow all methods.

  • Do not include OPTIONS — the gateway manages all preflight requests automatically.

How the gateway handles requests

Preflight requests (OPTIONS)

The gateway validates the Origin, Access-Control-Request-Method, and Access-Control-Request-Headers headers:

  • Validation passes: Returns 204 No Content with the configured CORS headers. Does not invoke the function.

  • Validation fails:

    • Origin matches but other headers do not: The gateway sets basic CORS headers, then forwards the request to the function.

    • Origin does not match: No CORS headers are set. The request is forwarded to the function.

Simple requests (GET, POST, HEAD, etc.)

The gateway validates only the Origin header:

  • Validation passes: Injects Access-Control-Allow-Origin and other CORS headers into the response. Forwards the request to the function.

  • Validation fails: Does not inject CORS headers. Still forwards the request to the function.

Priority

When multiple CORS handling methods apply to the same path, the gateway applies them in this order:

  1. API Configured CORS (highest priority): If enabled, the gateway applies this configuration first.

  2. Default CORS: If API Configured CORS is disabled, the gateway uses the built-in default echo behavior.

  3. Function-defined CORS: Headers returned by your function are merged with the above results.

HTTP trigger vs. API Gateway trigger

Both HTTP triggers and API Gateway triggers support building web applications.

HTTP triggerAPI Gateway trigger
Best forLightweight, direct HTTP-to-function pathWhen you need API Gateway features such as traffic management or request transformation
Path routingMap URL paths to your function by binding a custom domain nameConfigure Function Compute as the API backend
DocumentationConfigure a custom domain nameUse Function Compute as an API backend service

HTTP triggers offer these advantages over API Gateway triggers:

  • Faster to set up and easier to debug, with no additional gateway configuration.

  • No JSON encoding or decoding overhead — HTTP triggers pass requests and responses directly.

  • Compatible with standard HTTP testing tools.

  • Integrates easily with webhook-enabled services such as CDN origin fetch and Simple Message Queue (formerly MNS).

FAQ

Where do I configure the listening port?

Configure the listening port only when creating the function as a Web Function.

My function takes too long. How do I fix it?

The cause depends on the pattern:

My function returns HTTP status code 499. How do I handle this?

A 499 means the client closed the connection before the function responded. After a 499 error, the function instance restarts — configure health checks to prevent unnecessary restarts. See Why does the function instance restart after a client 499 error?

If client-side timeouts are the root cause, move the time-consuming logic to a separate function and invoke it asynchronously, or switch to asynchronous invocation from the client side.

I updated my function's configuration. When does it take effect?

Configuration updates take effect after the current execution completes. Requests already in progress use the old configuration until they finish; new requests use the updated configuration.

Alternatively, delete the current function and create a new one with the updated configuration.

Why does my API call fail after I add OPTIONS to `allowMethods`?

Do not add OPTIONS to corsConfig.allowMethods. The gateway manages all preflight requests automatically. Manually including OPTIONS causes request-handling errors.

After configuring API Configured CORS, OPTIONS requests return 200 instead of 204. Why?

Confirm that your account has been granted invitational preview access. If the gateway plugin is not fully activated, the gateway falls back to default CORS behavior, which returns 200 and forwards the request to your function.

**Can I use subdomain wildcards in allowOrigins, for example *.example.com?**

No. Subdomain wildcards are not supported. List all required domains explicitly in the allowOrigins array, or use https://* for broad HTTPS origin matching.

My function code also sets CORS headers. Will there be conflicts?

No. Gateway-generated headers and function-returned headers are merged. If duplicates exist, browsers use the first compliant value. Existing applications continue to work during migration.