Sub topic 11
Enabling CORS for browser clients
This chapter assumes you have deployed the ItemsApi and ItemsFunction from the SAM chapter, and that you know HTTP headers and basic JavaScript fetch. By the end you will be able to configure CORS on an HTTP API, test preflight requests with curl, and diagnose the usual browser errors.
Why browsers block cross-origin calls
An origin is the combination of scheme, host and port. https://example.com and https://example.com:8443 are different origins, and so are http://example.com and https://example.com. A web page at https://example.com that calls your API at https://abc123.execute-api.us-east-1.amazonaws.com is making a cross-origin request.
By default, the browser's same-origin policy lets the request go out but hides the response from the page's JavaScript. Cross-Origin Resource Sharing (CORS) is the protocol that lets a server tell the browser which origins may read its responses. Three points shape everything below:
- CORS is enforced by the browser. curl, Postman and server-to-server calls ignore it, so an API can work in curl and still fail in a browser.
- CORS is not authentication. It limits which web pages may read responses in a browser. It does not stop anyone else from calling your API.
- The server only sends headers. The browser decides whether to allow the page to see the response.
Simple requests and preflight
Some requests are sent directly, and the browser then checks the response headers. These are GET, HEAD or POST requests that use only a few "safe" headers and a content type of text/plain, multipart/form-data or application/x-www-form-urlencoded.
Most API calls are not simple. A POST with content-type: application/json, or any request with an authorization header, triggers a preflight. The browser first sends an OPTIONS request that asks permission:
Origin: the page's origin.Access-Control-Request-Method: the method the real request will use.Access-Control-Request-Headers: the custom headers the real request will carry.
If the response approves all three, the browser sends the real request. If not, the real request is never sent, and the console shows a CORS error.
How HTTP APIs handle CORS
An HTTP API has built-in CORS support. When you configure it on the API, API Gateway does the following:
- It answers preflight
OPTIONSrequests itself, even if you defined noOPTIONSroute. Lambda is not invoked and you pay no function cost for preflights. - It adds the configured CORS headers to responses that come back from your integration.
- It ignores any CORS headers your Lambda function returns.
The third point catches many people. If you set access-control-allow-origin in your handler and also configure CORS on the API, the API configuration wins and the handler's headers are discarded. Pick one place. For HTTP APIs, the API-level configuration is the better choice because it covers every route, including the error responses your code produces.
Configuration fields
| Field (SAM) | Response header | Notes |
|---|---|---|
| `AllowOrigins` | `Access-Control-Allow-Origin` | Exact origins, or `*`. Wildcard subdomains such as `https://*.example.com` are accepted. |
| `AllowMethods` | `Access-Control-Allow-Methods` | Methods the real request may use. |
| `AllowHeaders` | `Access-Control-Allow-Headers` | Must cover every custom header the page sends. |
| `ExposeHeaders` | `Access-Control-Expose-Headers` | Response headers the page's JavaScript may read. |
| `MaxAge` | `Access-Control-Max-Age` | Seconds the browser may cache the preflight result. |
| `AllowCredentials` | `Access-Control-Allow-Credentials` | Lets the page send cookies or other credentials. |
Configuring CORS in SAM
This replaces the ItemsApi resource from the earlier template. The function and its events stay the same.
ItemsApi:
Type: AWS::Serverless::HttpApi
Properties:
CorsConfiguration:
AllowOrigins:
- https://example.com
- http://localhost:3000
AllowMethods:
- GET
- POST
- OPTIONS
AllowHeaders:
- content-type
- authorization
ExposeHeaders:
- x-request-id
MaxAge: 600Notes on these values:
- List origins exactly as the browser sends them: scheme, host and optional port, with no trailing slash.
https://example.com/does not match. - Include
http://localhost:3000(or your dev server's port) only for development. Remove it from production templates, or define it in a separate stage's parameters. - Header names are case-insensitive, so
content-typeis fine. MaxAge: 600lets the browser reuse a preflight result for ten minutes. Browsers apply their own upper limits, so a large value may be capped.
Redeploy with sam deploy. CORS changes apply to the API itself, so no function code changes.
Credentials and wildcards
If the page sends cookies or uses fetch(url, { credentials: "include" }), you need AllowCredentials: true. The CORS specification then forbids * for origins, methods and headers. List each one explicitly. For a bearer token in the authorization header, you do not need credentials mode. You only need authorization in AllowHeaders.
Testing the preflight with curl
curl does not enforce CORS, but you can send the headers a browser would send and inspect the response. This is the quickest way to see what API Gateway returns.
API_URL="https://abc123.execute-api.us-east-1.amazonaws.com"
curl -i -X OPTIONS "$API_URL/items" \
-H 'Origin: https://example.com' \
-H 'Access-Control-Request-Method: POST' \
-H 'Access-Control-Request-Headers: content-type'A correct response is a 204 status with access-control-allow-origin: https://example.com, access-control-allow-methods and access-control-allow-headers. If you change the Origin to one that is not in your list, the allow headers are missing, and a browser would reject it.
Then send the actual request with an Origin header and confirm that access-control-allow-origin appears on the response.
curl -i -X POST "$API_URL/items" \
-H 'Origin: https://example.com' \
-H 'content-type: application/json' \
-d '{"name": "widget"}'Calling the API from a page
This is the browser side. It sends a JSON POST, which triggers a preflight, and reads a response header you exposed.
async function createItem() {
const response = await fetch(
"https://abc123.execute-api.us-east-1.amazonaws.com/items",
{
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ name: "widget" }),
}
);
console.log(response.status, response.headers.get("x-request-id"));
console.log(await response.json());
}
createItem().catch((err) => console.error("Request failed:", err));Without x-request-id in ExposeHeaders, the headers.get call returns null, even if the header is on the wire.
Common errors
- "No 'Access-Control-Allow-Origin' header is present." The origin is not in
AllowOrigins, or CORS is not configured at all. Compare the origin in the error to your list character by character, including port and scheme. - "Request header field authorization is not allowed." Add the header to
AllowHeaders. - "Method PUT is not allowed." Add the method to
AllowMethods. - Preflight succeeds but the real request fails with a CORS error on a 4xx or 5xx. The browser reports the failure as CORS, but the real cause is often a Lambda error or an authorizer rejection. Open the browser's network tab, then check the API's access logs and the function's CloudWatch Logs.
- Preflight returns 401 or 403 on a protected route. Browsers send preflights without credentials. Test the preflight with curl as shown above. If the authorizer is rejecting it, check how your routes and authorizers are set up, because an authorizer attached to a catch-all route can interfere.
- Header changes have no effect. Your Lambda response headers are being ignored because API-level CORS is configured. Change the template instead.
- Old behavior persists after a fix. The browser may be caching the preflight for
MaxAgeseconds. Hard-reload, or disable the cache in developer tools.
Exercise
A page at https://app.example.com sends fetch() with method PUT and an x-api-version header to your HTTP API. The API's CORS config has AllowOrigins: [https://app.example.com], AllowMethods: [GET, POST], AllowHeaders: [content-type]. Your Lambda handler also returns access-control-allow-methods: PUT. Does the call work, and what do you change?
Show answer
It fails at the preflight. API-level CORS is configured, so the handler's CORS headers are ignored. The preflight asks for PUT and x-api-version, but the API allows only GET and POST and the content-type header. Add PUT to AllowMethods and x-api-version to AllowHeaders in the CorsConfiguration, redeploy, and remove the CORS header from the handler.
Exercise
Your curl request to POST /items works, but the browser reports a CORS error for the same call. Give two reasons this can happen and how to check each.
Show answer
First, curl does not enforce CORS, so the missing or mismatched CORS headers only matter in the browser. Send an OPTIONS request with Origin and Access-Control-Request-* headers and check that the allow headers come back. Second, the origin, a method, or a header may not match the configuration, for example a trailing slash, a different port, or the authorization header missing from AllowHeaders. Compare the console error text with the CorsConfiguration values.