CORS issue - API and web on different domains

Hey guys,

I’m trying to deploy a redwood app to AWS. Due to design reasons, I would like to have the api in api.mydomain.com and the web in mydomain.com or www.mydomain.com.

The thing is that when I fetch the graphql function from mydomain.com to api.mydomain.com I get a CORS error:

Access to fetch at 'https://mydomain.io/dev/functions/graphql' from origin 'https://www.mydomain.io' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

So, I need to add to the graphql Function response headers:

 `'Access-Control-Allow-Origin': '*'
 'Access-Control-Allow-Credentials': true`

But I didn’t found a way of adding the headers.

I found here that is posible to pass options to the createHandler method in apollo-server-lambda.

The questions to solve are:

  • Is there a way to pass these options in src/function/graphql.js file to createHandler?
  • Is there another strategy to handle cors on graphql.js?

Thanks!

1 Like

Hi @leoalbin.

If CORS is enabled per apollo-server-lambda’s instructions I confirmed that I did get the response headers … I just inspected http://localhost:8911/graphql for a quick check.

Before Change

Screenshot 2020-07-31 07.08.01

After Change

Screenshot 2020-07-31 07.11.53

The Change

In redwoodjs/redwood/packages/api/src/functions/graphql.ts, add cors options in createHandler:

createHandler({
    cors: {
      origin: '*',
      credentials: true,
    },
  })

I’ll tried to enable CORS via the createGraphQLHandler’s callback and options but no luck (but I may not be doing it correctly).

I wonder @peterp if CORS should be enabled as the default behavior? Or perhaps make it an option to set origin: true or origin: * and the credentials?

1 Like