Hey there! You're using an out-of-date browser, so this site probably looks pretty funny. Upgrade your browser for the full experience.
dev header

WordPress REST API: Secure ajax calls custom endpoints


Here’s a handy guide to making secure ajax calls to custom REST endpoints.

As you may have heard, the WordPress REST API is now included out-of-the-box as of WP 4.7. That means no more plugins or other workarounds to use it!

It’s also super easy to add custom API endpoints which means the sky is the limit for custom functionality.

Recently, on one of our client’s WordPress sites, we developed a small form that submitted, via ajax, to a custom API endpoint. We wanted to make sure the endpoint was secure from external sources, which turns out to be pretty easy using WordPress nonces.

Step 1: Create the nonce

Create a globally accessible Javascript variable with a new nonce value.

var nonce = '<?php echo wp_create_nonce('wp_rest'); ?>';

Note: It has to be called wp_rest

Step 2: Pass the nonce with your ajax request

Make sure you pass the query string parameter _wpnonce as part of your ajax request.

With jQuery, it might look something like this:
$.getJSON(`/wp-json/me/v1/endpoint/?_wpnonce=${nonce}`, function (data) {
//do something with the response data
});

Step 3: Verify the nonce on the backend

In your custom endpoint, use the check_ajax_referer function to verify the nonce is valid.

check_ajax_referer('wp_rest', '_wpnonce');

The default behavior is for the script to immediately die if the nonce is invalid. You can do the following if you’d like to return an error or do something else more friendly.

if (!check_ajax_referer('wp_rest', '_wpnonce', false)) {
//error handling stuff
}

Did you expect more steps?

That’s all you have to do. Now go and secure your custom endpoints.

Born and raised in
Louisville, Kentucky.

502.498.8470

223 S. Clay St

Work With Us

  • This field is for validation purposes and should be left unchanged.