wp-graphql-cors icon indicating copy to clipboard operation
wp-graphql-cors copied to clipboard

CORS policy + apollo client

Open victormattosvm opened this issue 3 years ago • 4 comments

CORS policy + GraphQL + apollo client

I'm getting an error of CORS policy when using preflight request. The authorization headers are only being returned in preflight, but not in the standard request, causing the error.

I've been testing and my conclusion is that:

  1. I tried to add fetchOptions: { mode: 'no-cors' } to the Apollo client, but it doesn't allow the fetchPolicy to be no-cors when making a 'POST' request, so preflight will always be sent in this case. Unavoidable.
  2. The WP GraphQL plugin checks if the headers have already been sent and since they have already been sent to preflight, they are not resent in the official request. When receiving the response from the second request, the headers are not present, causing an error.

It happens because of "headers_sent" function that makes the "prepare_headers" function to be ignored.
File: wp-graphql/src/Router.php::506

My temporary solution: I had to force the two headers to be sent in the standard request. Always.

function add_cors_http_header() {
	$http_origin = $_SERVER['HTTP_ORIGIN'];

	if ( $http_origin && ( $http_origin == "https://domain1.com" || $http_origin == "https://domain2.com" ) )
	{  
		header("Access-Control-Allow-Origin: $http_origin");
		header( 'Access-Control-Allow-Credentials: true' );
	}
}
add_action( 'graphql_process_http_request', 'add_cors_http_header' );

victormattosvm avatar Jan 28 '22 11:01 victormattosvm

We stopped use this plugin when we just added enabled CORS on all domains in our theme. Is that something that you would do?

See: https://github.com/funkhaus/fuxt-backend/blob/master/functions/gql-functions.php#L110-L136

drewbaker avatar Jan 28 '22 22:01 drewbaker

Hello Drew, exactly! Thanks for your code. It'll be useful.

victormattosvm avatar Jan 28 '22 23:01 victormattosvm

Hi @drewbaker,

Would you still use the plugin if you needed to use your loginWithCookies mutation or are you handling that in a different way now?

scottyzen avatar Feb 02 '22 10:02 scottyzen

The WordPress login functions don't handle same site settings of cookies very well. So we use this: https://github.com/MikhailRoot/samesite-cookie-manager

But not sure if that plays nicely with the login mutation from this plugin.

drewbaker avatar Mar 16 '22 19:03 drewbaker

We added the ability to set the sameSite option into our theme, if anyone is curious.

https://github.com/funkhaus/fuxt-backend/blob/master/functions/cookie-manager.php

drewbaker avatar Feb 05 '23 16:02 drewbaker