Implement Web Method Caching

Web method caching is an effective way to improve the performance of your site by temporarily storing the return values of web methods in a cache. This article guides you through the process of implementing web method caching and how to invalidate it when necessary.

Step 1 | Set up caches

You must assign identifiers to cached return values of your web methods and can optionally define a cache's Time To Live (TTL). These required identifiers, called tags, allow you to easily identify caches that may need invalidation. For example, you can invalidate all caches that have the tag "math."

To set up caching for your web methods:

  1. Open your web modules and find the methods you want to cache.

  2. For each web method that you want to cache, update the code so that the webMethod() is called with the following options:

  • cache: An object containing:

    • tags: One or more identifiers of the cached return value.
    • ttl: The cache's time-to-live in seconds. If omitted, defaults to 1 week (604800 seconds).
    Copy

Important: The tags field is required for caching. If omitted, nothing is cached.

Step 2 | Invalidate caches

Invalidating or clearing your caches causes your backend methods to re-execute upon the following request, ensuring that fresh data is retrieved and cached.

To invalidate caches, use the invalidateCache() method from the wix-cache-backend module. This method accepts the invalidationMethods parameter, which specifies the tags previously assigned to the caches you want to invalidate.

Important:

  • You must specify invalidationMethods when invalidating your cache.
  • A cache can be assigned multiple tags. Any cache with at least one tag specified in the invalidationMethods object is invalidated when invalidateCache() is called.
  • The invalidateCache() method must be elevated and wrapped in a web method.

To invalidate caches:

  1. Add the necessary imports in your web modules (backend files).

    Copy
  2. Create a variable to store the tags assigned to the cache. Then call elevate() and store its returned value in another variable.

    Copy
  3. Call webMethod() and store its return value in an exported variable. Pass a permissions value and the elevated invalidation method.

    Copy

Notes:

  • The wix-cache-backend API, allows you to invalidate web method caches as well as router caches.
  • To invalidate the server side rendering (SSR) cache of your site, refer to the invalidateCache() method in the wix-site-backend module.

See also

Did this help?