phpwordpresswordpress-rest-apiwpengine

Wordpress REST API Caching Issue - WP Engine


I have created a custom plugin that actually just registeres a few API endpoints.

Right now the issue I'm having is that all of the endpoints are working fine locally, but when I push this code to WpEngine where I've hosted my WordPress site the API responses are getting cached.

If I clear the cache through WPEngine and make the request again the API is working fine until a 200 success response is received for the first time, once success is received then from the point the endpoint is always returning the same response no matter what header, parameter value I give to that endpoint.

In the wp-config.php file I've disabled the cache - define( 'WP_CACHE', false );

also tried adding

wp_cache_flush(); nocache_headers();

in the request action call back functions too, still no success, always the response are cached.

Few Code snippets for your reference -

// This is the route I've registered

public function register_routes()
{
   register_rest_route($namespace, '/config' ,[
                'methods' => 'GET',
                'callback' => array($this, 'Action_GetConfig'),
                'permission_callback' => 'authCheck'
            ]);
}

add_action( 'rest_api_init', array( $this, 'register_routes' ) );


        function Action_GetConfig(WP_REST_Request $request)
        {
            try {
                // wp_cache_flush();
                // nocache_headers();
  
                    $headers = $request->get_headers();

                    // Basic Validation
                    if (IsNullOrEmptyString($headers['platform'][0]) or IsNullOrEmptyString($headers['version'][0])) {
                        $resp = new WP_HTTP_Response();
                        // $resp->set_headers( array('Cache-Control' => 'no-cache, must-revalidate, max-age=0'));
                        $resp->set_status(400);
                        return $resp;
                    }
        
                    // Service Invocation
                    $results = $this->getConfig($headers['platform'][0], $headers['version'][0]);
                    $resp = new WP_HTTP_Response($results);
                    $resp->set_status(200);
                    return $resp;

            } catch (Throwable $e) {
                //$log->error($e);
                $resp = new WP_HTTP_Response($e);
                $resp->set_status(500);
                return $resp;
            }
        }

Can someone help in solving this API response caching issue? Thanks!


Solution

  • I solved this issue by adding a Cache Exclusion Policy in WPEngine. Because by default in WPEngine all the Endpoints responses are cached. So if we want NOT to cache a specific route, then we have to add that route to the Exclusion list.

    path: ^/wp-json/nx/services/?
    

    I added this above Route RegEx in WPEngine.