WordPress REST API CORS Issues Solved

Last Updated:
Key in lock

This post contain affiliate links to Udemy courses, meaning when you click the links and make a purchase, I receive a small commission. I only recommend courses that I believe support the content, and it helps maintain the site.

Are you using WordPress as a headless CMS? Are you trying to work with REST API, but be as secure as possible? Are you getting the following CORS header errors:

“Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.”

“X has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: It does not have HTTP ok status.”

“Request header field x-wp-nonce is not allowed by Access-Control-Allow-Headers in preflight response.”

I found this as well! Mainly due to WordPress not being the simplest thing to use when dealing with the REST API and CORS security.

 

The solution is this:

add_action('init', 'handle_preflight');
function handle_preflight() {
    $origin = get_http_origin();
    if ($origin === 'https://yourfrontenddomain') {
        header("Access-Control-Allow-Origin: yourfrontenddomain");
        header("Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE");
        header("Access-Control-Allow-Credentials: true");
        header('Access-Control-Allow-Headers: Origin, X-Requested-With, X-WP-Nonce, Content-Type, Accept, Authorization');
        if ('OPTIONS' == $_SERVER['REQUEST_METHOD']) {
            status_header(200);
            exit();
        }
    }
}
add_filter('rest_authentication_errors', 'rest_filter_incoming_connections');
function rest_filter_incoming_connections($errors) {
    $request_server = $_SERVER['REMOTE_ADDR'];
    $origin = get_http_origin();
    if ($origin !== 'https://yourfrontenddomain') return new WP_Error('forbidden_access', $origin, array(
        'status' => 403
    ));
    return $errors;
}

Add this to your WordPress function.php file and you should be set!

Remember to update the text ‘yourfrontenddomain’ to the domain you are using on the front end.

Hopefully this solves your WordPress CORS issue!

If you have any thoughts on this or want to chat, find me @robertmars

Related Posts

Helpful Bits Straight Into Your Inbox

Subscribe to the newsletter for insights and helpful pieces on React, Gatsby, Next JS, Headless WordPress, and Jest testing.