0

I'm building a custom Rest Api endpoint. User can call this endpoint via ajax request in the frontend together with nonce value which was created by

wp_localize_script( 'some-js', 'wpApiSettings', [
       'nonce' => wp_create_nonce( 'wp_rest' ),
    ],
] );

The problem is the caching plugin. In my case, I've used breeze.

It cache the page together with nonce value. When the nonce is expired, the page cache still have the expired nonce in it. So when the used this nonce, they receive rest_cookie_invalid_nonce until the cached is cleared.

Is there a way to prevent this from happen?

1 Answer 1

0

Instead of adding the nonce to the script you can get the nonce using an ajax request. That way the script is cached, but each user gets a different nonce via the response. Just make sure the ajax response isn't being cached by your plugin.

add_action( 'wp_ajax_get_nonce', 'generate_nonce' );    
function generate_nonce(){
    $nonce = wp_create_nonce('my-nonce');
    echo $nonce;
    wp_die();
}   

Then use something like this in your javascript.

var nonce;
jQuery(function() {
    jQuery.get(ajaxurl+'?action=get_nonce', function(data){ 
        nonce = data;
    });
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.