• Resolved stevejonk

    (@stevejonk)


    Hi!

    I am using your nice plugin and the api response is still slow.
    After some debugging I found out that the difference occurs when sending a long the X-Wp-Nonce header in the request.

    Am I correct in the statement that a cache isn’t hit/created when it is for a logged in user (or at least when that header is sent along)?

    And if yes, is this by design? Or can I fix this in a way that the cached response is also sent to requests by logged in users?

    Thanks in advance! ??

    The page I need help with: [log in to see the link]

Viewing 3 replies - 1 through 3 (of 3 total)
  • Thread Starter stevejonk

    (@stevejonk)

    Ahh and of course after asking for help I see other posts where it’s stated that requests with Nonce aren’t cached.

    Can I overrule this in a way for some endpoints?

    My /posts endpoint contains a lot of data, which is all static for. I only want to restrict non-users of viewing it.

    Plugin Author Richard Korthuis

    (@rockfire)

    Hi @stevejonk

    Thank you for using our plugin!

    Yes you can make our plugin also cache requests with a nonce, using the wp_rest_cache/skip_nonce_caching filter like this:

    /**
    * Always allow caching of requests with a nonce.
    *
    * @param bool             $skip_nonce_caching False if cache should not be skipped when nonce is present.
    * @param \WP_REST_Request $request The current REST Request.
    * @param string           $request_uri The REST URI that is being requested.
    *
    * @return boolean
    */
    function wprc_skip_nonce_caching( $skip_nonce_caching, $request, $request_uri ) {
        $skip_nonce_caching = false;
    
        return $skip_nonce_caching;
    }
    
    add_filter( 'wp_rest_cache/skip_nonce_caching', 'wprc_skip_nonce_caching', 10, 3 );

    There are however some things you have to keep in mind when using this filter:

    • First of all because of the way our plugin works, this filter has to be in a must use plugin (in the mu-plugins directory) which is alphabetically before wp-rest-cache.php Otherwise it will not work.
    • Second: because if a endpoint is cached (and caching isn’t skipped for whatever reason) the cache is returned without any other code being executed. So if you still want to check if a user is logged in, you would have to do this check somewhere in the function that is called by the filter. So return false only if the user is logged in and return true if the user isn’t logged in so no cache is used (and the user will not see the results).
    Thread Starter stevejonk

    (@stevejonk)

    @rockfire Thanks a lot for this fast and helpful response!
    Will implement this! ??

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Cache not hit when nonce is in header’ is closed to new replies.