Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Next.js and React

Apollo Client is blocked by CORS when the GraphQL server runs on AWS Lambda

ErrorCross-Origin Request Blocked

Short answer

Apollo Server does not set CORS for you when it runs behind a framework or integration, and on Lambda that layer is API Gateway. For an HTTP API, turn CORS on for the API itself. For a REST API, return the headers from the Lambda result. With cookies, allow one named origin instead of a wildcard.

  • Applies to Apollo Server 4 with @as-integrations/aws-lambda, Apollo Client HttpLink, Amazon API Gateway HTTP API and REST API
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 1Find out which cause you have

    Send the preflight that the browser sends before a JSON POST, straight at the API Gateway URL. An HTTP API returns CORS headers only when the request has an Origin header, and an OPTIONS request also needs Access-Control-Request-Method. Read which Access-Control headers come back.

    curl -i -X OPTIONS https://a1b2c3d4.execute-api.eu-west-1.amazonaws.com/ \
      -H "Origin: https://www.example.com" \
      -H "Access-Control-Request-Method: POST" \
      -H "Access-Control-Request-Headers: content-type"
  2. 2Match what you see, then jump to its fix

    1. 1The preflight returns no Access-Control-Allow-Origin header, and the API type is HTTP APIAn HTTP API has no CORS configurationFix
    2. 2Your handler or middleware sets Access-Control-Allow-Origin, yet the browser sees a different value or ignores your changeHeaders set in the Lambda are ignored because the HTTP API has its own CORS configurationFix
    3. 3The API is a REST API (not an HTTP API), and the POST response from curl has no Access-Control-Allow-Origin headerA REST API with Lambda proxy integration, and the Apollo result has no CORS headersFix
    4. 4HttpLink has credentials: 'include' and the response says Access-Control-Allow-Origin: *Apollo Client sends cookies, but the server answers with a wildcard originFix
    5. 5The preflight fails, and a header listed in its Access-Control-Request-Headers is missing from Access-Control-Allow-Headers in the answerThe headers Apollo Client sends are not in the allowed headersFix

What does the error look like?

  • Cross-Origin Request Blocked
  • No 'Access-Control-Allow-Origin' header is present on the requested resource.
  • GraphQL requests from the browser fail, while the same query sent with curl returns data

Cause 1 of 5

An HTTP API has no CORS configuration

1Check

Apollo's own docs leave CORS to the framework or integration you use. In front of a Lambda, that is API Gateway. Read the CORS configuration stored on the API; null or empty output means none is set.

aws apigatewayv2 get-api --api-id a1b2c3d4 --query CorsConfiguration

2Fix

Set the CORS configuration on the HTTP API. API Gateway then answers the preflight itself, even without an OPTIONS route, and adds the headers to the real response. In a Serverless Framework project, the Apollo docs enable it with cors: true under the HTTP API provider settings.

aws apigatewayv2 update-api \
  --api-id a1b2c3d4 \
  --cors-configuration AllowOrigins=https://www.example.com,AllowMethods=POST,GET,OPTIONS,AllowHeaders=content-type,authorization

# serverless.yml, the Apollo docs form
provider:
  httpApi:
    cors: true

3Verify

Run the preflight from the first step again; Access-Control-Allow-Origin should now list your origin.

curl -is -X OPTIONS https://a1b2c3d4.execute-api.eu-west-1.amazonaws.com/ -H "Origin: https://www.example.com" -H "Access-Control-Request-Method: POST" | grep -i access-control

Confirmed by docs.aws.amazon.com

Did this fix it?

Cause 2 of 5

Headers set in the Lambda are ignored because the HTTP API has its own CORS configuration

1Check

Once CORS is configured on an HTTP API, API Gateway ignores CORS headers that come back from the backend integration. Compare the origin in your code with the one stored on the API.

aws apigatewayv2 get-api --api-id a1b2c3d4 --query CorsConfiguration.AllowOrigins

2Fix

Make the change where it counts: in the API's CORS configuration. Remove the duplicate header code from the function so there is one source of truth.

aws apigatewayv2 update-api \
  --api-id a1b2c3d4 \
  --cors-configuration AllowOrigins=https://www.example.com,https://admin.example.com

3Verify

The preflight response lists the origin you just configured.

curl -is -X OPTIONS https://a1b2c3d4.execute-api.eu-west-1.amazonaws.com/ -H "Origin: https://admin.example.com" -H "Access-Control-Request-Method: POST" | grep -i allow-origin

Confirmed by docs.aws.amazon.com

Did this fix it?

Cause 3 of 5

A REST API with Lambda proxy integration, and the Apollo result has no CORS headers

1Check

With a Lambda proxy integration the backend must return Access-Control-Allow-Origin, Access-Control-Allow-Methods and Access-Control-Allow-Headers itself. Apollo's Lambda integration lets middleware change the result before it is returned, which is the place to add them.

curl -is -X POST https://a1b2c3d4.execute-api.eu-west-1.amazonaws.com/prod/graphql -H "Origin: https://www.example.com" -H "Content-Type: application/json" -d '{"query":"{ __typename }"}' | grep -i access-control

2Fix

Add the headers in a middleware. The preflight request needs an answer with the same headers too; the AWS page describes an OPTIONS method with a mock integration that returns them.

import { startServerAndCreateLambdaHandler, handlers, middleware } from '@as-integrations/aws-lambda';

const requestHandler = handlers.createAPIGatewayProxyEventRequestHandler();

const addCors: middleware.MiddlewareFn<typeof requestHandler> = async () => {
  return async (result) => {
    result.headers = {
      ...result.headers,
      'Access-Control-Allow-Origin': 'https://www.example.com',
      'Access-Control-Allow-Headers': 'Content-Type,Authorization',
      'Access-Control-Allow-Methods': 'OPTIONS,POST,GET',
    };
  };
};

export const graphqlHandler = startServerAndCreateLambdaHandler(server, requestHandler, {
  middleware: [addCors],
});

3Verify

Deploy, then repeat the POST from the check. The header should now be in the response.

curl -is -X POST https://a1b2c3d4.execute-api.eu-west-1.amazonaws.com/prod/graphql -H "Origin: https://www.example.com" -H "Content-Type: application/json" -d '{"query":"{ __typename }"}' | grep -i access-control-allow-origin

Confirmed by docs.aws.amazon.com

Did this fix it?

Cause 4 of 5

Apollo Client sends cookies, but the server answers with a wildcard origin

1Check

Apollo Client passes credentials to fetch when HttpLink sets credentials. A browser refuses a credentialed response that uses the wildcard origin, and the server must also allow credentials. Check the client link and the server's origin setting.

grep -rn "credentials" src/ | grep -i "httplink\|include\|same-origin"

2Fix

Allow the named front-end origin with credentials on the server. If the front end is on another domain, keep credentials: 'include' on the link.

// client
const link = new HttpLink({
  uri: 'https://a1b2c3d4.execute-api.eu-west-1.amazonaws.com/',
  credentials: 'include',
});

# server (HTTP API)
aws apigatewayv2 update-api --api-id a1b2c3d4 \
  --cors-configuration AllowOrigins=https://www.example.com,AllowCredentials=true,AllowMethods=POST,AllowHeaders=content-type

3Verify

The preflight shows your single origin and Access-Control-Allow-Credentials: true, not *.

curl -is -X OPTIONS https://a1b2c3d4.execute-api.eu-west-1.amazonaws.com/ -H "Origin: https://www.example.com" -H "Access-Control-Request-Method: POST" | grep -i access-control

Confirmed by apollographql.com

Did this fix it?

Cause 5 of 5

The headers Apollo Client sends are not in the allowed headers

1Check

Access-Control-Allow-Headers in the preflight answer decides which request headers the real request may carry. The headers the browser lists in Access-Control-Request-Headers must all be allowed. Apollo's docs also say a client may send an Apollo-Require-Preflight header, so include that name if you use it.

curl -is -X OPTIONS https://a1b2c3d4.execute-api.eu-west-1.amazonaws.com/ -H "Origin: https://www.example.com" -H "Access-Control-Request-Method: POST" -H "Access-Control-Request-Headers: authorization,content-type" | grep -i access-control-allow-headers

2Fix

Add each header the client sends to the allowed headers of the API.

aws apigatewayv2 update-api --api-id a1b2c3d4 \
  --cors-configuration AllowOrigins=https://www.example.com,AllowMethods=POST,GET,OPTIONS,AllowHeaders=content-type,authorization,apollo-require-preflight

3Verify

Repeat the check; Access-Control-Allow-Headers should list all three names.

curl -is -X OPTIONS https://a1b2c3d4.execute-api.eu-west-1.amazonaws.com/ -H "Origin: https://www.example.com" -H "Access-Control-Request-Method: POST" -H "Access-Control-Request-Headers: authorization,content-type" | grep -i access-control-allow-headers

Confirmed by developer.mozilla.org

Did this fix it?

How do I stop it coming back?

  • Decide once where CORS lives (the API Gateway CORS configuration for an HTTP API) and keep headers out of the function code.
  • List real origins, one per environment, instead of a wildcard, and add https://studio.apollographql.com only if you use Apollo Studio Explorer against the API.
  • Keep the preflight curl command from the first step in your deploy checklist.
  • Treat CORS as a browser rule: a query that works in curl or Postman proves nothing about the browser.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine built on the same technologies:

Related fixes

Web apps

A POST to a Google Apps Script web app returns 405 or a CORS error

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Apps Script web apps run doPost for POST and doGet for GET, and the Apps Script guides describe no other entry points.

3 causes, each with a fix

Web apps

A Chrome extension content script cannot read another site's response

Access to fetch at 'https://api.example.com/price' from origin 'https://shop.example.net' has been blocked by CORS policy

Since Chrome 85 a content script's request is treated as a request from the web page it runs in, so the page's CORS rules apply and the extension's host permissions do not help.

3 causes, each with a fix

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.