← All posts

WordPress REST API: 401 and CORS errors with fetch()

Your JavaScript gets a 401 or a CORS block when calling the WordPress API? They have different causes and precise fixes.

WordPress REST API: 401 and CORS errors with fetch()

Key points

  • 401: the request is not authenticated; the nonce or credentials are missing.
  • CORS: the browser blocks a call from another domain.
  • On the same site, the wp_rest nonce is enough; from another app, use application passwords.

Reading public posts through the REST API works straight away. Trouble starts when you write data or call the API from another app. Two errors come up again and again: 401 and CORS.

401 from your own site

Being logged in is not enough: the REST API ignores the session cookie unless the request carries a nonce. Pass it from PHP and send it as a header:

// PHP
wp_localize_script('my-script', 'WTS', [
    'root'  => esc_url_raw(rest_url()),
    'nonce' => wp_create_nonce('wp_rest'),
]);

// JavaScript
const res = await fetch(WTS.root + 'wp/v2/posts', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': WTS.nonce },
  credentials: 'same-origin',
  body: JSON.stringify({ title: 'Draft', status: 'draft' }),
});

401 from another application

For a SaaS or external script, use application passwords (Profile → Application Passwords) with Basic auth, always over HTTPS. If the Authorization header never arrives, some Apache setups strip it: add SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1 to .htaccess.

CORS errors

CORS is a browser safeguard, not a WordPress error. If your app runs on app.example.com and the API on www.example.com, the server must allow that exact origin:

add_action('rest_api_init', function () {
    remove_filter('rest_pre_serve_request', 'rest_send_cors_headers');
    add_filter('rest_pre_serve_request', function ($v) {
        $ok = ['https://app.example.com'];
        $o = get_http_origin();
        if (in_array($o, $ok, true)) {
            header('Access-Control-Allow-Origin: ' . $o);
            header('Access-Control-Allow-Credentials: true');
            header('Vary: Origin');
        }
        return $v;
    });
}, 15);

Never use * with credentials: browsers refuse it, and it is unsafe.

FAQ

Why does Postman work but not the browser?

Postman does not enforce CORS. Only browsers block cross-origin requests.

Does the nonce expire?

Yes, after 12 to 24 hours. For pages left open a long time, fetch a fresh nonce before sending.

Facing this on your site? We diagnose and fix it without putting your content at risk.

Share LinkedIn Facebook X WhatsApp
</>

webtestudio

Web agency: custom WordPress sites, premium themes and SaaS software.

Discuss your project →