WordPress Nonce Verification Failed? Log the Real Cause

When WordPress nonce verification fails, you rarely get anything useful back. A form shows “The link you followed has expired”, admin-ajax.php returns -1, or the REST API sends rest_cookie_invalid_nonce. None of these tells you which action failed, for which user, or why. So you end up guessing: page cache, an old tab, a typo in the action name, a user who logged in again in another browser.

The snippet below hooks into wp_verify_nonce_failed, an action WordPress core fires every time a non-empty nonce doesn’t match. It works out the most likely cause by rebuilding the nonce hashes, then keeps the last 50 failures. You can read them under Tools > Nonce failures, and in debug.log too if WP_DEBUG_LOG is on. Put it in a small plugin, an mu-plugin, or your theme’s functions.php while you debug.

The snippet

<?php
/**
 * Plugin Name: DPC Nonce Failure Log
 * Description: Records why wp_verify_nonce() failed and lists it under Tools > Nonce failures.
 */

defined( 'ABSPATH' ) || exit;

add_action( 'wp_verify_nonce_failed', 'dpc_nonce_log_failure', 10, 4 );
add_action( 'admin_menu', 'dpc_nonce_admin_menu' );
add_action( 'admin_post_dpc_nonce_clear', 'dpc_nonce_clear_log' );

/**
 * The same hash wp_verify_nonce() builds for one tick.
 */
function dpc_nonce_hash( int $tick, $action, int $uid, string $token ): string {
	return substr( wp_hash( $tick . '|' . $action . '|' . $uid . '|' . $token, 'nonce' ), -12, 10 );
}

/**
 * Does the nonce match any tick from $from down to $to?
 */
function dpc_nonce_matches( string $nonce, int $from, int $to, $action, int $uid, string $token ): bool {
	for ( $tick = $from; $tick >= $to; $tick-- ) {
		if ( hash_equals( dpc_nonce_hash( $tick, $action, $uid, $token ), $nonce ) ) {
			return true;
		}
	}
	return false;
}

/**
 * Work out why a nonce failed. Returns a reason code.
 */
function dpc_nonce_diagnose( string $nonce, $action, int $uid, string $token, bool $logged_in ): string {
	if ( 10 !== strlen( $nonce ) || ! ctype_xdigit( $nonce ) ) {
		return 'malformed';
	}

	$tick = (int) wp_nonce_tick( $action );
	$max  = max( 2, (int) apply_filters( 'dpc_nonce_lookback_ticks', 14 ) );

	// Right user, right action, right session, but too old.
	if ( dpc_nonce_matches( $nonce, $tick - 2, $tick - $max, $action, $uid, $token ) ) {
		return 'expired';
	}

	// Built for a logged-out visitor (usually a cached page), checked for a logged-in user.
	if ( $logged_in ) {
		$guest = (int) apply_filters( 'nonce_user_logged_out', 0, $action );
		if ( dpc_nonce_matches( $nonce, $tick, $tick - $max, $action, $guest, '' ) ) {
			return 'logged_out';
		}
	}

	// Built with wp_create_nonce() and no action, which defaults to -1.
	if ( '-1' !== (string) $action && dpc_nonce_matches( $nonce, $tick, $tick - 1, -1, $uid, $token ) ) {
		return 'no_action';
	}

	return 'unknown';
}

/**
 * Runs on every failed wp_verify_nonce() call with a non-empty nonce.
 */
function dpc_nonce_log_failure( $nonce, $action, $user, $token ): void {
	if ( ! apply_filters( 'dpc_nonce_log_enabled', true, $action ) ) {
		return;
	}

	$user_id   = $user instanceof WP_User ? (int) $user->ID : 0;
	$logged_in = $user_id > 0;
	$uid       = $logged_in ? $user_id : (int) apply_filters( 'nonce_user_logged_out', 0, $action );

	$uri  = isset( $_SERVER['REQUEST_URI'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '';
	$path = (string) wp_parse_url( $uri, PHP_URL_PATH );
	if ( wp_doing_ajax() && isset( $_REQUEST['action'] ) ) {
		$path .= ' (ajax: ' . sanitize_key( wp_unslash( $_REQUEST['action'] ) ) . ')';
	}

	$method  = isset( $_SERVER['REQUEST_METHOD'] ) ? strtoupper( sanitize_key( wp_unslash( $_SERVER['REQUEST_METHOD'] ) ) ) : 'CLI';
	$referer = wp_get_raw_referer();

	$entry = array(
		'time'    => time(),
		'action'  => substr( (string) $action, 0, 100 ),
		'reason'  => dpc_nonce_diagnose( (string) $nonce, $action, $uid, (string) $token, $logged_in ),
		'user'    => $user_id,
		'request' => substr( $method . ' ' . $path, 0, 200 ),
		'referer' => $referer ? substr( (string) wp_parse_url( $referer, PHP_URL_PATH ), 0, 200 ) : '',
	);

	$log = get_option( 'dpc_nonce_failures', array() );
	$log = is_array( $log ) ? $log : array();
	array_unshift( $log, $entry );
	update_option( 'dpc_nonce_failures', array_slice( $log, 0, 50 ), false );

	if ( defined( 'WP_DEBUG_LOG' ) && WP_DEBUG_LOG ) {
		error_log( sprintf( 'Nonce failed: action "%s", reason %s, user %d, %s', $entry['action'], $entry['reason'], $user_id, $entry['request'] ) );
	}
}

function dpc_nonce_reason_label( string $reason ): string {
	return match ( $reason ) {
		'malformed'  => 'Not a nonce: cut off, double-encoded or replaced by other data.',
		'expired'    => 'Expired: right user and action, but older than the nonce lifetime.',
		'logged_out' => 'Made for a logged-out visitor (cached page?), checked for a logged-in user.',
		'no_action'  => 'Made with wp_create_nonce() without an action.',
		default      => 'Wrong action, another login session, or checked after logout.',
	};
}

function dpc_nonce_admin_menu(): void {
	add_management_page( 'Nonce failures', 'Nonce failures', 'manage_options', 'dpc-nonce-failures', 'dpc_nonce_render_page' );
}

function dpc_nonce_render_page(): void {
	if ( ! current_user_can( 'manage_options' ) ) {
		wp_die( esc_html__( 'Sorry, you are not allowed to access this page.' ), 403 );
	}

	$log = get_option( 'dpc_nonce_failures', array() );
	$log = is_array( $log ) ? $log : array();

	echo '<div class="wrap"><h1>Nonce failures</h1>';

	if ( ! $log ) {
		echo '<p>No failed nonce checks recorded.</p></div>';
		return;
	}

	echo '<table class="widefat striped"><thead><tr><th>Time</th><th>Action</th><th>Likely cause</th><th>User</th><th>Request</th><th>Referer</th></tr></thead><tbody>';

	foreach ( $log as $row ) {
		$user_id = (int) ( $row['user'] ?? 0 );
		$user    = $user_id ? get_userdata( $user_id ) : false;
		$who     = $user ? $user->user_login : ( $user_id ? '#' . $user_id : 'logged out' );

		printf(
			'<tr><td>%s</td><td><code>%s</code></td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>',
			esc_html( (string) wp_date( 'Y-m-d H:i:s', (int) ( $row['time'] ?? 0 ) ) ),
			esc_html( (string) ( $row['action'] ?? '' ) ),
			esc_html( dpc_nonce_reason_label( (string) ( $row['reason'] ?? '' ) ) ),
			esc_html( $who ),
			esc_html( (string) ( $row['request'] ?? '' ) ),
			esc_html( (string) ( $row['referer'] ?? '' ) )
		);
	}

	echo '</tbody></table>';
	echo '<form method="post" action="' . esc_url( admin_url( 'admin-post.php' ) ) . '" style="margin-top:1em">';
	echo '<input type="hidden" name="action" value="dpc_nonce_clear">';
	wp_nonce_field( 'dpc_nonce_clear', '_wpnonce', false );
	echo '<button type="submit" class="button">Clear log</button></form></div>';
}

function dpc_nonce_clear_log(): void {
	if ( ! current_user_can( 'manage_options' ) ) {
		wp_die( esc_html__( 'Sorry, you are not allowed to do that.' ), 403 );
	}

	check_admin_referer( 'dpc_nonce_clear' );
	delete_option( 'dpc_nonce_failures' );

	wp_safe_redirect( admin_url( 'tools.php?page=dpc-nonce-failures' ) );
	exit;
}

How it works

A WordPress nonce is the last 10 characters of a hash built from four things: a time tick, the action, the user ID and the login session token. wp_verify_nonce() accepts the current tick and the one before it. With the default one-day lifetime, a tick is 12 hours. If neither matches, it fires wp_verify_nonce_failed with the nonce, the action, the user and the token.

The diagnosis rebuilds the hash with one input changed at a time:

  • Expired: it matches an older tick for the same user, action and session. The page sat open too long, or a cache kept it past the lifetime. Long-lived screens may need a longer lifetime for that action; see WordPress Nonce Lifetime: Change Expiration per Action.
  • Logged out: it matches user 0 with an empty session token. The visitor got a page cached for guests and then submitted it while logged in. Exclude that page from the cache, or fetch a fresh nonce over AJAX.
  • No action: it matches action -1. Someone called wp_create_nonce() with no argument but verifies against a named action.
  • Malformed: the value isn’t 10 hex characters at all. Look for a field name clash, a URL-encoded value, or JavaScript sending the wrong variable.

Anything else is logged as unknown. That usually means the action name differs between creation and verification, or the user logged in again and got a new session token. WordPress stores only hashes of session tokens, so the old session can’t be rebuilt to confirm it.

The admin side follows the rules it debugs. The page and the clear handler both check manage_options, the clear button carries its own nonce checked with check_admin_referer(), and every logged value is escaped with esc_html() on output. The log doesn’t store the nonce itself or the query string of the request, only the path.

Customise it

  • Log only the actions you’re chasing: add_filter( 'dpc_nonce_log_enabled', fn( $on, $action ) => 'wp_rest' === $action, 10, 2 );
  • Long nonce lifetimes need a deeper look-back to spot expiry: raise dpc_nonce_lookback_ticks (default 14 ticks, a week at the default lifetime).
  • Change the 50 in array_slice() to keep more or fewer entries.

Gotchas

  • An empty nonce never reaches the hook, because core returns false before firing it. If a failure never shows up in the log, the field or X-WP-Nonce header isn’t being sent at all.
  • REST requests with an invalid X-WP-Nonce are logged under the action wp_rest. When you’re logged in and see rest_cookie_invalid_nonce, a cached nonce is the usual cause. For locking down the REST API itself, see WordPress REST API Restricted to Authenticated Users.
  • Every failure writes to an option. Bots posting junk to forms can cause a lot of writes, so remove the snippet or switch it off with the filter when you’re done debugging.

Snippet poll. Should this snippet be in the Scripts Organizer library for one-click import? 10 votes put it there.

0 of 10 votes

// newsletter

Three tested WordPress snippets a week

Blocks, security, performance, Tailwind, PHP and React. Copy, paste, ship. You’ll also get DPlugins product updates. No spam, and you can unsubscribe anytime.

// newsletter

Three tested WordPress snippets a week

Blocks, security, performance, Tailwind, PHP and React. Copy, paste, ship. You'll also get DPlugins product updates. No spam, and you can unsubscribe anytime.