WordPress REST API: Secure ajax calls custom endpoints


Mark Biek

on 5/9/2017

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.

Share to

Related Posts

Custom Dev
Dynamic Select Fields with Advanced Custom Fields
Dynamic Select Fields with Advanced Custom Fields

By:Nick Stewart on 12/8/2021

In Advanced Custom Fields, there is the Post Object field that allows you to select a post resource from your WordPress website. This field can return the actual post object or the post ID.

Read More »
Custom Bootstrap Shortcodes for WordPress

By: Natalie Miller on 6/27/2017

Bootstrap shortcodes are a quick way to make your WordPress content more dynamic.

Read More »