wp-graphql-cors
wp-graphql-cors copied to clipboard
CORS policy + apollo client
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:
- 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.
- 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' );
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
Hello Drew, exactly! Thanks for your code. It'll be useful.
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?
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.
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