DEV Community

Robert Marshall
Robert Marshall

Posted on • Originally published at robertmarshall.dev on

8 1

WordPress REST API Cors Issues

Most up to date post is here: https://robertmarshall.dev/blog/wordpress-rest-api-cors-issues

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.”

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

The solution is this:

<?php add_action('init', 'handle_preflight');
function handle_preflight() {
    $origin = get_http_origin();
    if ($origin === 'https://yourfrontenddomain') {
        header("Access-Control-Allow-Origin: " . HEADLESS_FRONTEND_URL);
        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, 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;
}
?>
Enter fullscreen mode Exit fullscreen mode

Hope it helps!

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (8)

Collapse
 
rbosamiya9 profile image
Ravindra Bosamiya

still facing issue 😞 using localhost, wasted a day help me.

Collapse
 
robmarshall profile image
Robert Marshall

Did you add localhost to your function? Either localhost or localhost

Collapse
 
rbosamiya9 profile image
Ravindra Bosamiya

hey, i solved my error by changing my shared hosting service, i was using free service of infinityfree but then i changed to 000webhostapp its working fine.

Collapse
 
johnlewisdesign profile image
johnlewisdesign

Legend mate thank you.

I was caught up trying to send header authentication from ReactJS to WooCommerce REST API via fetch() - nearly did it, but this finally got me there.

Collapse
 
robmarshall profile image
Robert Marshall

Glad this helped! :)

Collapse
 
champernet profile image
Timur Iskakov

Thanks'! This is a day-saving article for me!

Collapse
 
differentmonster profile image
differentMonster

i should put this code on my wp-content/themes/twentytwentyone/functions.php and under if ( ! function_exists( 'twenty_twenty_one_setup' ) ) ?

Collapse
 
differentmonster profile image
differentMonster

anyone got github folder i can check out ?

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay