Implement Router Caching

Router caching in an effective strategy to improve your site's performance by temporarily storing the return values from the ok() method, which contain the same page data that is sent as the response to a router request. When visitors access a router page, the system can quickly deliver the cached data, enabling faster page loads and a better overall user experience. This article guides you through the process of implementing router caching and how to invalidate it when necessary.

Step 1 | Set up your cache

You must assign identifiers to router caches 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 "dress-page."

To set up caching for your routers:

  1. Open the router.js file in your backend code and find the routers you want to cache.

  2. In the request for each router page you want to cache, create a variable representing the options parameter to store the cache object. Include the following fields in the cache object:

    • 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).
  3. In the return statement of the router request, pass the variable holding the cache object to the ok() method.

    Copy

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

Step 2 | Invalidate caches

Invalidating or clearing your caches triggers the routing and rendering process upon the following next, ensuring that your caches hold the most up-to-date page data.

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 caches. Any cache with at least one tag specified in the invalidationMethods object will be 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 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?