WP REST API: check if user is logged in

You shouldn’t pass your nonce to your JavaScript to verify it, since client side scripts can be easily manipulated. Instead, you should get the nonce from your front-end content, and then pass it to server to verify it.

After verification, you should decide to output content by server, not by your JavaScript file.

Something like this:

if ( is_user_logged_in() ) {
    if ( wp_verify_nonce($_REQUEST['X-WP-Nonce'], 'wp_rest') {
        // Nonce is correct!
    } else {
        // Don't send the data, it's a trap!
    }
}

As a side note, REST API offers its own method to fetch the passed queries. So, you can get it this way in your callback function:

function foobar( \WP_REST_Request $request ) {
    $nonce = $request['X-WP-Nonce'];
}

Leave a Comment