Verify Nonces and Sanitize Input in WordPress AJAX Handlers

Verify nonces and sanitize input in WordPress AJAX handlers

AJAX requests in WordPress go to admin-ajax.php, which any visitor can call. So every handler must check where the request comes from and what it contains. A CSRF attack makes the browser of a logged-in user send a forged request to your site; a nonce, a token tied to the action and the user, is the standard protection. And everything in $_POST and $_GET is untrusted until it is sanitized.

Problem: A custom AJAX handler without a nonce check and input sanitization can be called by forged requests and receives unprocessed data.

Solution: Pass a nonce to JavaScript with wp_localize_script(), check it with check_ajax_referer() at the start of the handler, check the user’s rights for anything that changes data, sanitize every value, and answer with wp_send_json_success() / wp_send_json_error().

PHP

<?php
// The script and its settings
add_action( 'wp_enqueue_scripts', function () {
    wp_enqueue_script( 'my-ajax', get_stylesheet_directory_uri() . '/js/ajax.js', array(), '1.0', true );
    wp_localize_script( 'my-ajax', 'myAjax', array(
        'ajaxurl' => admin_url( 'admin-ajax.php' ),
        'nonce'   => wp_create_nonce( 'my_ajax_nonce' ),
    ) );
} );

// For logged-in users and for guests
add_action( 'wp_ajax_my_search', 'handle_my_search' );
add_action( 'wp_ajax_nopriv_my_search', 'handle_my_search' );

function handle_my_search() {
    check_ajax_referer( 'my_ajax_nonce', 'nonce' ); // stops with 403 if the nonce is wrong

    $search = sanitize_text_field( wp_unslash( $_POST['search'] ?? '' ) );
    if ( mb_strlen( $search ) < 2 ) {
        wp_send_json_error( array( 'message' => 'Query too short' ), 400 );
    }

    $posts = get_posts( array( 's' => $search, 'posts_per_page' => 10, 'post_status' => 'publish' ) );

    wp_send_json_success( array_map( function ( $post ) {
        return array(
            'id'    => $post->ID,
            'title' => get_the_title( $post ),
            'url'   => get_permalink( $post ),
        );
    }, $posts ) );
}

// An action that changes data: only for logged-in users with the right capability
add_action( 'wp_ajax_my_save_note', function () {
    check_ajax_referer( 'my_ajax_nonce', 'nonce' );

    $post_id = absint( $_POST['post_id'] ?? 0 );
    if ( ! current_user_can( 'edit_post', $post_id ) ) {
        wp_send_json_error( array( 'message' => 'Forbidden' ), 403 );
    }

    update_post_meta( $post_id, '_my_note', sanitize_textarea_field( wp_unslash( $_POST['note'] ?? '' ) ) );
    wp_send_json_success();
} );

The second argument of check_ajax_referer() is the name of the request field with the nonce. If the nonce is missing or wrong, the function stops the request with -1 and status 403. wp_send_json_*() set the JSON header and end the request, so no wp_die() is needed after them.

JavaScript

async function mySearch( query ) {
    const body = new URLSearchParams( { action: 'my_search', nonce: myAjax.nonce, search: query } );
    const response = await fetch( myAjax.ajaxurl, { method: 'POST', body } );
    const json = await response.json();
    return json.success ? json.data : [];
}

action selects the hook: my_search → wp_ajax_my_search / wp_ajax_nopriv_my_search.

NOTE: A nonce is not authorization. For guests it is the same for all logged-out visitors, and anyone can get it from the page. It protects logged-in users from CSRF; who may do what is decided only by current_user_can(). And on cached pages the nonce in the HTML can expire (it lives 12–24 hours): exclude such pages from the cache, or check the nonce only for logged-in users. The same input rules are described in more detail in sanitizing and validating user input.