DEV Community

Cover image for What is a WordPress Nonce? And how to use it.
Simon Lee
Simon Lee

Posted on • Updated on

What is a WordPress Nonce? And how to use it.

A nonce by definition is something that is used only once and without recurrence. In a WordPress website, nonces are used to validate the contents of a form and avoid malicious activity. More specifically, a nonce protects your website from Cross-Site Request Forgeries (CSRFs) attacks.

How to use a nonce in WordPress

In functions.php, in your function that loads scripts and css files, you can create a nonce property inside a WordPress function called wp_localize_script(). See example below:

wp_localize_script('my-website-files', 'someSiteData', array(
  'nonce' => wp_create_nonce('wp_rest')
));
Enter fullscreen mode Exit fullscreen mode

If you view your web page source, you can find a key-value that looks similar to: var someSiteData = {"nonce": "15e935b62e"}

You can use that generated hash as a property in an AJAX request, as shown below:

// jQuery
$.ajax({
  beforeSend: (xhr) => {
    xhr.setRequestHeader('X-WP-Nonce', someSiteData.nonce);
  }
})
Enter fullscreen mode Exit fullscreen mode

Top comments (0)