Use the Fetch API to call the WordPress REST API from JavaScript

Call the WordPress REST API from JavaScript with fetch()

The WordPress REST API gives posts, pages, terms, users, comments and custom post types as JSON at /wp-json/wp/v2/. In themes it used to be called with jQuery.ajax(), but the native fetch() works in all current browsers, returns a Promise and reads well with async/await, so jQuery is not needed for it.

Problem: Load posts and change data from the theme’s JavaScript without jQuery.

Solution: Pass the REST root URL and a nonce to the script from PHP. Read public data with a plain fetch(); for changes send the nonce in the X-WP-Nonce header, so WordPress recognizes the logged-in user.

Pass the settings from PHP

<?php
add_action( 'wp_enqueue_scripts', 'ha_localise_rest_config' );

function ha_localise_rest_config() {
    wp_enqueue_script( 'ha-rest-script', get_stylesheet_directory_uri() . '/js/rest.js', array(), '1.0', true );

    wp_localize_script( 'ha-rest-script', 'haRest', array(
        'root'  => esc_url_raw( rest_url() ),
        'nonce' => wp_create_nonce( 'wp_rest' ),
    ) );
}

rest_url() gives the correct address even if the site is in a subfolder or permalinks are off.

Two helpers

// js/rest.js
async function restGet( path ) {
    const response = await fetch( haRest.root + path );
    if ( ! response.ok ) {
        throw new Error( 'REST GET failed: ' + response.status );
    }
    return response.json();
}

async function restWrite( method, path, data ) {
    const response = await fetch( haRest.root + path, {
        method,
        headers: {
            'Content-Type': 'application/json',
            'X-WP-Nonce': haRest.nonce,
        },
        body: JSON.stringify( data ),
    } );
    if ( ! response.ok ) {
        const error = await response.json().catch( () => ( {} ) );
        throw new Error( error.message || 'REST request failed: ' + response.status );
    }
    return response.json();
}

fetch() does not reject on HTTP errors (404, 403, 500), only on network failures, so response.ok must be checked. For errors WordPress returns JSON with code and message.

Examples

// The 5 latest posts; _fields keeps the response small
async function loadRecentPosts() {
    const posts = await restGet( 'wp/v2/posts?per_page=5&_fields=id,title,link' );
    const list = document.querySelector( '#recent-posts' );

    posts.forEach( ( post ) => {
        const li = document.createElement( 'li' );
        const a = document.createElement( 'a' );
        a.href = post.link;
        a.innerHTML = post.title.rendered; // the title comes already escaped by WordPress
        li.appendChild( a );
        list.appendChild( li );
    } );
}

// Change the title of a post (the user must be logged in and allowed to edit it)
async function updatePostTitle( postId, newTitle ) {
    const post = await restWrite( 'POST', `wp/v2/posts/${ postId }`, { title: newTitle } );
    console.log( 'Updated:', post.title.rendered );
}

// Create a draft
async function createDraftPost( title, content ) {
    const post = await restWrite( 'POST', 'wp/v2/posts', { title, content, status: 'draft' } );
    console.log( 'Created post ID:', post.id );
}

loadRecentPosts().catch( ( error ) => console.error( error ) );

Authentication

With cookies alone the REST API treats the request as anonymous: the X-WP-Nonce header is what tells WordPress which logged-in user is calling. Without it, write requests return 401. For external applications (another site, a mobile app) there are Application Passwords, added in WordPress 5.6, with Basic authentication instead of cookies.

NOTE: The wp_rest nonce is tied to the user and lives 12 to 24 hours. If a page with the nonce is served from a page cache, visitors get someone else’s or an expired nonce, and the write requests fail with rest_cookie_invalid_nonce. Exclude such pages from the cache or fetch a fresh nonce with an AJAX request. And whatever the script sends, check it again in PHP: the REST endpoint is the real boundary, not your JavaScript.